3

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?

Sakib Arifin
  • 255
  • 2
  • 13
Ross
  • 617
  • 2
  • 9
  • 23
  • input `EOF` (`ctrl + z` or `ctrl + d`) and enter – BLUEPIXY Aug 05 '14 at 14:31
  • @BLUEPIXY is it possible to do it without the use of EOF? for instance a new user using the program doesnt add EOF? And is there any other method which avoids making use of EOF(which might not use 'while') – Ross Aug 05 '14 at 14:48
  • input like this `12 345 132 123.`. `.` as input end mark.(`scanf` fails when it is input) – BLUEPIXY Aug 05 '14 at 14:51

4 Answers4

8

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();
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
4
//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;
}
  • number needs to be used in the while loop I.E. while( i < number) and the scanf statement as the body of the while loop I.E. scanf("%d", &array[i++]); otherwise we are right back to the infinite loop problem – user3629249 Aug 06 '14 at 04:15
1

You should try to write your statement like this:

while ( ( scanf("%d",&array[i++] ) != -1 ) && ( i < n ) ) { ... }

Please note the boundary check.

As people keep saying, scanf is not your friend when parsing real input from normal humans. There are many pitfalls in its handling of error cases.

See also:

Community
  • 1
  • 1
Adrian
  • 6,013
  • 10
  • 47
  • 68
0

There is nothing wrong with your code as it stands. And as long as the number of integers entered does not exceed the size of array, the program runs until EOF is entered. i.e. the following works:

int main(void)
{
    int array[20] = {0};
    int i=0;
    while(scanf("%d", &array[i++]) == 1);
    return 0;   
}  

As BLUEPIXY says, you must enter the correct keystroke for EOF.

ryyker
  • 22,849
  • 3
  • 43
  • 87