In said:
In said:
Just be aware of the following:
1. fgets() will only read as many characters as you specify. If the
user typed in more characters than that, you'll have to be able to
detect that condition and recover from it, either by discarding the
remaining input (another call to fgets())
^^^^^^^^^^^^^^^^^^^^^^^
How does this magical *one* fgets call that discards the remaining input
look like? This is a trivial job for [f]scanf, but I wasn't aware that
fgets can do it, too.
Additional calls to fgets() or other input routine of your choice.
Better?
Much better.
Which is why you wrap fgets() in a lot of other logic to build robust
I/O routines.
But then, why bother with fgets in the first place? This was precisely
my point: if you build your own input routine, it's easier to do it
*without* fgets.
No, fgets() isn't a magic bullet. Neither is *scanf().
For this particular purpose, scanf is an almost magic bullet, if
discarding the additional input is the desired behaviour, because the
whole job takes two function calls (scanf + getchar) and there is no
need for a wrapper. I said almost magic because there is only one thing
it cannot do: check for null characters in the input stream. Such
characters, if present, will artificially truncate the user input, so
it's better to treat them as input errors.
All C I/O
routines suck in their own special way. All require more support
logic than they should.
Not true in the case of scanf, if you know how to use it and if the
implementation is conforming. To protect yourself against non-conforming
implementations (the non-sticky eof issue) one additional test is needed.
Ideal solution (assumes a conforming implementation):
char buff[100 + 1] = "";
int rc = scanf("%100[^\n]%*[^\n]", buff);
getchar();
Safer real world solution:
int rc = scanf("%100[^\n]%*[^\n]", buff);
if (!feof(stdin)) getchar();
In either case, rc == EOF if the user pressed the eof key when prompted
for input.
Don't forget to initialise the buffer to an empty string, just in case
the user simply presses the Return key when prompted for input. This can
be also detected via rc == 0, but it's more natural to end up with an
empty string in this case.
Dan