0

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?

2
  • 2
    That's not a well-formed XML, btw. attribute values should be enclosed in quotes. Commented 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 ? Commented Oct 3, 2009 at 21:12

2 Answers 2

2

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++).

Sign up to request clarification or add additional context in comments.

4 Comments

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 / ?
If I could I'd give you 1 point extra for checking the return value of sscanf()
@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.
so I can't do: sscanf(theString, "<operator value=%s/>", &string)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.