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?
-
2That's not a well-formed XML, btw. attribute values should be enclosed in quotes.Mehrdad Afshari– Mehrdad Afshari2009-10-03 21:05:47 +00:00Commented Oct 3, 2009 at 21:05
-
might not be xml. Is the string supposed to be a snippet of Xml ? or is it some legacy, like sgml ?Andrew Keith– Andrew Keith2009-10-03 21:12:00 +00:00Commented Oct 3, 2009 at 21:12
2 Answers
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++).
4 Comments
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.