0

I am a Java programmer, but currently solving some online problems on C platform. I want to stop reading input when no input is read from console. Its like this

Input : 1
2
3
4

Output : 1
2
3
4

But in advance, I do not know how many no.s I will read. As many of you may be knowing that online judges feed input from a file. So how to stop reading data from console when no data is fed from console ?

Sorry for very stupid question.

2
  • Will the input be a single line? Then read about fgets. Commented Sep 6, 2014 at 12:47
  • no, my bad ...post edited Commented Sep 6, 2014 at 12:49

1 Answer 1

2

scanf reference:

Upon successful completion, these functions shall return the number of successfully matched and assigned input items; this number can be zero in the event of an early matching failure. If the input ends before the first matching failure or conversion, EOF shall be returned. If a read error occurs, the error indicator for the stream is set, EOF shall be returned.

#include <stdio.h>

int x;
while (scanf("%d", &x) != EOF) { ... }

Live demo link

Sign up to request clarification or add additional context in comments.

1 Comment

Better to test against the number of assignemnts: while (scanf("%d", &x) == 1) /* ... */. scanf() can return 0 to indicate some error not caught with != EOF

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.