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?

3
  • input EOF (ctrl + z or ctrl + d) and enter Commented Aug 5, 2014 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') Commented Aug 5, 2014 at 14:48
  • input like this 12 345 132 123.. . as input end mark.(scanf fails when it is input) Commented Aug 5, 2014 at 14:51

4 Answers 4

9

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();
}
Sign up to request clarification or add additional context in comments.

Comments

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;
}

1 Comment

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
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:

1 Comment

even this code runs into into infinite loop without the use of EOF
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.