B
Ben Bacarisse
Andrew McMeikan said:William said:I wanted to limit how many chars I read in, but the code below instead of stopping at
7 chars will happily read 30 or 40 car lines and spit them out. Not what I expected.
Any pointers?#include <stdio.h>
int main(void){
char line [100];
while (NULL!=fgets(line,8,stdin))
{
printf("%s",line);
}
return 0;
}
How could you expect this program to do anything other
than what you describe? Each pass through the loop
it reads up to 7 chars from stdin and prints them.
Sometimes, it reads less than 7 chars, but there's
no way for you to tell in the output since
you can't distinguish between
"abcdefgh" and "abcdefgh". (in the first case,
I typed "abc", then "def", then "gh", but in
the second I typed "abcd", then "efgh".) What
behavior did you expect?
I expected that if I typed 123456789 I would get 1234567 out.
I threw in a \n in the printf and it now makes some sense.
Still not behaving how I hoped having the 89 spill over is not what
I wanted, just wanted a nice safe way of inputing size limited
fields.
It is doing that. What you also seemed to want was to throw away any
input that remains on the line. This is quite a separate issue. The
usual way of to write a function like:
void discard_input(FILE *fp)
{
int c;
while ((c = fgetc(fp)) != '\n' && c != EOF);
}
though you might prefer one that returns an indication of why it
finished. Of course, you must only use this function of the input you
get does not already include a '\n'.
A "bigger picture" description of what you are trying to do would help
you get better answers.