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.
fgets()
then parse the input buffer to get integers.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.