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?
views:
104answers:
2
+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
2009-10-03 21:06:53
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
2009-10-03 21:19:35
If I could I'd give you 1 point extra for checking the return value of sscanf()
pmg
2009-10-03 21:26:35
@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
2009-10-03 21:28:27
goe
2009-10-03 21:37:42
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
2009-10-03 21:11:02