0
#include <stdio.h>
int main() 
{
    int a[50],i,n=0;
    while(scanf("%d",&a[n++])!=EOF);
    n--;
    for(i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }
    return 0;
}

Let,

Input: 5 6 7 8 9

Output: 5 6 7 8 9

My question is why the above code works in Online C Compiler and gives proper EOF(-1)

But while running the code in offline C IDE like Codeblocks, it results in an infinite loop of input as it is not giving any EOF, and what to do to get a similar result in an offline compiler?

11
  • 6
    Isn't it because you are not giving any EOF (Ctrl+Z on Windows or Ctrl+D on Linux)? Commented Jul 23, 2020 at 15:15
  • 5
    As an alternative to: while(scanf("%d",&a[n++])!=EOF); you can do while(scanf("%d",&a[n++])==1);. Then the loop will stop at the first non-integer input. Commented Jul 23, 2020 at 15:17
  • 2
    You should also check that n is always less than 50 Commented Jul 23, 2020 at 15:18
  • 5
    Also adding size check is good: while(n < 50 && scanf("%d",&a[n++])==1); Commented Jul 23, 2020 at 15:18
  • 2
    Another reason to check the specific 1 from scanf is that if you enter data it cannot convert you'll go into an infinite loop, since 0 != EOF too. Commented Jul 23, 2020 at 15:20

1 Answer 1

1

The scanf() function returns the number of input values it scanned.

In case of input error or failure it returns EOF. As suggested in the comments you can compare the scanf() return value to 1 in order to see if it had a valid input. So if your input is anything other than an int it will end the loop.

Also making sure n is still within the array bounds before calling the scanf() is a good idea.

So you can write the code like this

#include <stdio.h>

int main ()
{
    int a[50], n = 0;

    while((n < 50) && (scanf("%d", &a[n++]) == 1));

    n--;

    for (int i = 0; i < n; i++)
    {
        printf("%d", a[i]);
    }
    
    return 0;
}
Sign up to request clarification or add additional context in comments.

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.