tags:

views:

104

answers:

2

I'm getting this string as an input "<operator value=1/>". How in C can I parse out this string to get the "1" back?

+1  A: 

If you know that that's exactly the type of string you'll always get, you can just use sscanf():

int value;
if(sscanf(theString, "<operator value=%d/>", &value) == 1)
    ;  // parsing succeeded, use value
else
    ;  // parsing failed

If you're going to be receiving more complex input, I recommend using an XML parsing library such as expat or TinyXML (requires C++).

Adam Rosenfield
But I need to extract the "1". This value may differ from time to time. So the String will look the same but the value can change. Can I still use sscanf to just retrieve whatever is between = and / ?
goe
If I could I'd give you 1 point extra for checking the return value of sscanf()
pmg
@goe: Yes, if the value you're looking for is an integer, this will accept any integer in place of "1". If you're looking for a string in general, you'll have to something more complex.
Adam Rosenfield
goe
A: 

i am assuming your parsing the string without using any library and the string may not be legal. I once encountered this problem when parsing sgml.

there are a few ways to do this. You could use strstok to split the string to find the value 1, then convert it using atoi.

I would recommend you use a regex library to extract the string. It would handle more boundary cases.

Andrew Keith