Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get integer input in an array using scanf in C?

Tags:

c

scanf

I am taking multiple integer inputs using scanf and saving it in an array

while(scanf("%d",&array[i++])==1);

The input integers are separated by white spaces for example:

12 345 132 123

I read this solution in another post.

But the problem is the while loop is not terminating.

What's the problem with this statement?

like image 786
Ross Avatar asked Jan 30 '26 06:01

Ross


2 Answers

OP is using the Enter or '\n' to indicate the end of input and spaces as number delimiters. scanf("%d",... does not distinguish between these white-spaces. In OP's while() loop, scanf() consumes the '\n' waiting for additional input.

Instead, read a line with fgets() and then use sscanf(), strtol(), etc. to process it. (strtol() is best, but OP is using scanf() family)

char buf[100];
if (fgets(buf, sizeof buf, stdin) != NULL) {
  char *p = buf;
  int n;
  while (sscanf(p, "%d %n", &array[i], &n) == 1) {
     ; // do something with array[i]
     i++;  // Increment after success @BLUEPIXY
     p += n;
  }
  if (*p != '\0') HandleLeftOverNonNumericInput();
}
like image 59
chux - Reinstate Monica Avatar answered Jan 31 '26 21:01

chux - Reinstate Monica


//Better do it in this way
int main()
{
  int number,array[20],i=0;
  scanf("%d",&number);//Number of scanfs
  while(i<number)
  scanf("%d",&array[i++]);
  return 0;
}
like image 38
Shreemay Panhalkar Avatar answered Jan 31 '26 21:01

Shreemay Panhalkar