Convert string of numbers to integers

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

So, I have a line: 1 2 3 4 /0
And now I need variables, so I can use them as an integer:a=1, a=2, a=3, a=4

How can i do this?

+3
source share
4 answers

If the line always contains 4 numbers, separated by spaces, then this can be done using sscanf:

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

If the number of numbers changes, you need to parse the string.

Please clarify your question.

+2
source

, , , , . sscanf, , . sscanf , 4.

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

buf "1 2 3" "1 2 a b" - , sscanf .

+4

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

First mark the line with spaces. The standard C method for this strtok () is :

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 this.

+3
source

sscanf () can do this.

#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);
}
+2
source

Source: https://habr.com/ru/post/1698564/


All Articles