0

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;
1
  • 2
    You probably need to learn one other concept called array. Commented Mar 25, 2014 at 23:10

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Would you dare to put here sample piece of code doing it? Otherwise your answer seems too short and would fit better into comment rather then as complete answer.
1

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" );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.