Saturday, May 22, 2010

A small c, c++ problem?

i have a string which has a pattern: "EmpId: %26lt;number%26gt;". I want to extract the number in an integer.


I tried sscanf(str, "%sEmpId: %d%s", front, %26amp;emp_id, rest);


This does not work if EmpId comes in the beginning of the sentence. I can fix this using strstr(). But i'd like to use only one string function. please help (C or C++ solution is fine)

A small c, c++ problem?
Try removing the first %s and the "front" argument - what's that for if the first word is always "Empld"?





Alternatively, use strtok to take the string apart token by token, eg use strtok( str, ": ") to get the "Empld" bit, then text = strtok( NULL, " " ) and atoi( text ) to get the number and so on.
Reply:I would search for the : character, and then do an atoi on the string from the point after that.





eg. Something like this:





char* ptr = strchr(str, ':');


int emp_id = 0;


if (ptr)


atoi(ptr+1);





You could put it in a function for ease of use.
Reply:I vote for regular expressions library if you want single function.
Reply:Are you looking for a regular expression ( http://en.wikipedia.org/wiki/Regular_exp... ). That is, do you only know the pattern, not the exact positioning of the expression?





In C++, I normally use Boost.Regex (http://en.wikipedia.org/wiki/Boost_libra... ) for Regexs. If you don't want to use Boost, then you will have to write your own mini regex parser.

blazing star

No comments:

Post a Comment