Iter Ator
Iter Ator

Reputation: 9334

read integer from character array

I have a string, whith five integers, separated by spaces. For example: 12 33 45 0 1

I have five variables, where I would like to load these numbers. Is it possible to call atoi more times? Or how is it even possible?

char c[] = "12 33 45 0 1";
int a1, a2, a3, a4, a5;

Upvotes: 0

Views: 140

Answers (2)

Benesh
Benesh

Reputation: 3428

Use strtok to split the string into tokens, and use atoi on each one of them.

A simple example:

    char c[] = "1 2 3";         /* our input */
    char delim[] = " ";         /* the delimiters array */
    char *s1,*s2,*s3;           /* temporary strings */
    int a1, a2, a3;             /* output */

    s1=strtok(c,delim);         /* first call to strtok - pass the original string */
    a1=atoi(s1);                /* atoi - converts a string to an int */

    s2=strtok(NULL,delim);      /* for the next calls, pass NULL instead */
    a2=atoi(s2);

    s3=strtok(NULL,delim);
    a3=atoi(s3);

The tricky thing about strtok is that we pass the original string for the first token, and NULL for the other tokens.

Upvotes: 5

user3386109
user3386109

Reputation: 34839

You can also use sscanf to convert the numbers, but be sure to check the return value

if ( sscanf( c, "%d%d%d%d%d", &a1, &a2, &a3, &a4, &a5 ) != 5 )
    printf( "Well, that didn't work\n" );

Upvotes: 1

Related Questions