Search code examples
carraysalgorithmscanfgetchar

Scanning values in C till hit a new-line char, '\n'


How can I scanf() the integer values I enter into an array until I hit enter.

I believe I can use getchar() != '\n'.

but how do I loop through the line ?

Suppose my input is 20 21 2 12 2. I want an array that has all those inputs. What given functions could I use in order to scan them all in.


Solution

    1. You are trying to read integers as characters so once read you need to convert it to integers.
    2. Read the line to a buffer using fgets() then parse the input buffer to get integers.
    3. Store the integers to the array.

    The code looks like

    char buf[300];
    int a[5],i=0;
    fgets(buf,sizeof(buf),stdin);
    char *p = strtok(buf," ");
    while(p != NULL)
    {
      char *endptr;
      a[i] = strtol(p,&endptr,10);
      if ((*endptr != '\0') && (isspace(*endptr) == 0))
          printf("warning: invalid value detected\n");
      else
          i++;
      p = strtok(NULL," ");
    }
    

    You can use the alternative strtol() instead of atoi() to convert string to integer.

    PS: Your buf should be large enough to hold the whole line. fgets() read till newline character.