# Thread: grabbing an int from a string

1. ## grabbing an int from a string

now i have a problem

if there is an equation like 12+13 in a string , how can i grab the int 12 and int 13 , each one alone

not int 1 , int 2

2. strtol for example

3. Well, if the equation has a predefined format like "a+b", you can simply use sscanf() to read the numbers just like you would from the shell. But if you're referring to reading numbers from any type of mathematical equation, you need to write a parser, which isn't very hard (for mathematical equations only) but probably too complicated for a beginner.

4. still not understanding ....

5. As in

char operator;
int a,b;
if ( sscanf( "12+13", "&#37;d%c%d", &a, &operator, &b ) == 3 )

6. You could tokenize the string.

There's a C function that goes something like this:

char *strtok( char *string1, const char *string2 );

Where string11 is the string you wish to tokenize (in this case, "12+13") and string2 is what you use to break up the string (in this case, "+"). This will basically read the string until it finds the "+" sign, stop there, and return that string, which is thus "12". Once this function returns NULL, you've finished tokenizing the string.

From there, you can use int atoi( const char *string ) to convert the resulting strings into integers.

Just for reference, to do this with the number 12, it would look somewhat similar to this:

number = atoi( strtok( string, "+" ) );

Here's a small tutorial on C tokenizing here on this site:
http://faq.cprogramming.com/cgi-bin/...&id=1044780608

I'm going on the assumption, though, that you do not necessarilly need the "+" sign, which may not be the case. This is just to start you off, I suppose.

7. char *strtok( char *string1, const char *string2 );
Don't use strtokk, it alters your string. Either u will have keep a backup of your original string or use sscanf();

ssharish2005