tags:

views:

601

answers:

5

I have a string (char) and I want to extract numbers out of it.

So I have string: 1 2 3 4 /0
And now I want some variables, so I can use them as integer: a=1, a=2, a=3, a=4

How can I do that?

+2  A: 

sscanf() can do that.

#include <stdio.h>

int main(void)
{
  int a, b, c, d;
  sscanf("1 2 3 4", "%d %d %d %d", &a, &b, &c, &d);
  printf("%d,%d,%d,%d\n", a, b, c, d);
}
Ignacio Vazquez-Abrams
+2  A: 

If the string always contains 4 numbers delimited with spaces, then it could be done with sscanf:

sscanf(string, "%d %d %d %d", &a, &b, &c, &d);

If the count of numbers varies, then you would need to parse the string.

Please clarify your question accordingly.

HS
Please note that sscanf() returns the number of successfully converted and assigned specifiers (it does not count those suppressed using '%*d' notation).
Jonathan Leffler
+2  A: 

As others have noted, if you know how many numbers to expect, sscanf is the easiest solution. Otherwise, the following sketches a more general solution:

First tokenize the string by spaces. The standard C method for this is strtok():

char* copy;
char* token;

copy = strdup(string); /* strtok modifies the string, so we need a copy */

token = strtok(copy, " ");
while(token!=NULL){
  /* token now points to one number.
  token = strtok(copy, " ");      
}

Then convert the string to integers. atoi() will do that.

Rasmus Faber
dont forget to clean up the created copy.
Tetha
I'd recommend using strtol() instead of atoi() since it has well-defined error handling. Also, strdup() is not a C standard function (it's in POSIX), though implementing your own strdup() is trivial. Of course, copy should be free()'d after.
Chris Young
+4  A: 

The answers given so far are correct, as long as your string is formatted the way you expect. You should always check the return value of sscanf to make sure things worked okay. sscanf returns the number of conversions successfully performed, in the above case 4.

if (4 != sscanf(buf, "%d %d %d %d", &a, &b, &c, &d))
{
    /* deal with error */
}

If buf was "1 2 3" or "1 2 a b" or something, sscanf would return a short item count.

Chris Young
A: 

sscanf solved my problem. Thank you all for the help.