tags:

views:

196

answers:

2

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 remove the quotes) and name is always empty. What am I doing wrong?

Thanks, code is appreciated.

Jess.

+2  A: 

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.

Jerry Coffin
that worked. I just need a small explanation. The first %*[^\"] gets rid of the string before the first "? then the \" is th first "... I'm getting all confused here.
Jessica
+1  A: 

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

lhf