I need to implement in C the program ,which reads an unknown number of lines from stdin.
I know that the maximum number of lines is 100.
I tried to use gets
,but I don`t know when to stop the loop.
Can you advise me how to implement it?
Asked
Active
Viewed 463 times
2

YAKOVM
- 9,805
- 31
- 116
- 217
-
What is the condition when you want to stop reading? – Marki555 Jan 13 '12 at 17:35
-
@davogotland - no.Ii is a part of the work – YAKOVM Jan 13 '12 at 17:38
-
3Do not use `gets()`; it is a recipe for disaster. Forget that you ever read anything about the function existing. Use `fgets()` instead (but remember to strip the newline that `fgets()` keeps but `gets()` removes). – Jonathan Leffler Jan 13 '12 at 17:41
-
What about maximum line length? – James Morris Jan 13 '12 at 18:21
1 Answers
1
This depends on when you want your program to stop. There are several common approaches:
- Never: you run an infinite loop until end-user hits
^C
or otherwise terminates your program using the facilities of your operating system - Until the user enters a special marker, i.e. a "keyword"
QUIT
,EXIT
, etc. on a line by itself - Until the user enters an empty line (i.e. hits
Enter
)
Since the max number in your case is 100, you can use it as the limit to automatically terminate the input once the max is reached.

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
-
@JonathanLeffler The `EOF` is definitely most common when you read from standard input. But the OP specifically mentions console, which suggests to me that he is writing an interactive program of some sort. – Sergey Kalinichenko Jan 13 '12 at 17:45
-
-
@Yakov The you should read to `EOF` or the limit, whichever is first, as Jonathan Leffler suggests in his "next most common" choice. When the program is run from a UNIX console, enter Control-D character at the start of a line to send `EOF` to your program's input. – Sergey Kalinichenko Jan 13 '12 at 18:06
-
@dasblinkenlight Pressing ctrl-D closes the input stream. You cannot "send EOF". When the input stream is closed, the program will invoke read(), which will return 0. If read() was invoked by a stdio function such as getchar(), that function will return EOF. If read was invoked by fread(), fread will return 0 and the program will call feof() to see if the end of file was reached. Saying "send EOF" perpetuates the myth that unix files contain an entry marking the end of the file. They do not. – William Pursell Jan 13 '12 at 19:16
-
@WilliamPursell Of course "sending an EOF" is a gross oversimplification. I wasn't aware of the silly myth about UNIX files containing some kind of an `EOF` marker, otherwise I'd be more careful with my choice of words. – Sergey Kalinichenko Jan 13 '12 at 19:36