how to use strtol to parse random number of ints in a string?

213 views Asked by At

I have a program that reads input with fgets:

#include <stdio.h>

int main() {
    char buf[128];
    fgets(buf, 128, stdin);
}

I would like the user to enter any amount of integers. However i am not sure how to parse them. I did some research and found strtol(). So my question is how can i use strtol to parse ints and print them? here is what i tried:


int main() {

    char buf[128];

    char *a = buf;
    char *b;
    fgets(buf, 128, stdin);

    while (1) {

          long x = strtol(a, &b, 10);
          printf("%ld ", x);
          a = b;

          if (b == buf+strlen(buf))
              break;
    }
1

There are 1 answers

0
Vlad from Moscow On

Take into account that according to the description of the function in the C Standard

7 If the subject sequence is empty or does not have the expected form, no conversion is performed; the value of nptr is stored in the object pointed to by endptr, provided that endptr is not a null pointer.

You can write something like shown in the demonstration program below

#include <stdio.h>
#include <stdlib.h>

int main( void )
{
    const char *s = "1 2 3 4 5 6 7 8 9 10";

    const char *p = s;
    while ( 1 )
    {
        char *next;

        long int x = strtol( p, &next, 10 );

        if (next != p)
        {
            printf( "%ld ", x );
            p = next;
        }
        else
        {
            break;
        }
    }
    putchar( '\n' );
}

The program output is

1 2 3 4 5 6 7 8 9 10