开发者

Using sscanf to parse two strings out

I have a semi xml formatted file that contains line with the following format:

<param name="Distance" value="1000Km" />

The first char in the string is usually a TAB or spaces. I've been using the following to try to parse the two strings out (from name and value):

if(sscanf(lineread, "\t<param name=\"%s\" value=\"%s\" />", name, value) == 1)
{
    //do something
}

name and value are char*

Now, the result is always the same: name gets parse (I need to remo开发者_运维问答ve the quotes) and name is always empty. What am I doing wrong?

Thanks, code is appreciated.

Jess.


As usual, a scanset is probably your best answer:

sscanf(lineread, "%*[^\"]\"%[^\"]\"%*[^\"]\"%[^\"]\"", name, value);

Of course, for real code you also want to limit the lengths of the conversions:

#include <stdio.h>

int main() { 
    char lineread[] = "<param name=\"Distance\" value=\"1000Km\" />";   
    char name[256], value[256];

    sscanf(lineread, "%*[^\"]\"%255[^\"]\"%*[^\"]\"%255[^\"]\"", name, value);

    printf("%s\t%s", name, value);
    return 0;
}

Edti: BTW, sscanf returns the number of successful conversions, so in your original code, you probably wanted to compare to 2 instead of 1.

Edit2: This much: %*[^\"]\" means "read and ignore characters other than a quote mark", then read and skip across a quote mark. The next %255[^\"]\" means "read up to 255 characters other than a quote mark, then read and skip across a quote mark. That whole pattern is then repeated to read the second string.


The problem with the original code was that %s stops only after seeing a space. Hence, name gets Distance" not Distance as expected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜