Quote:
Originally posted by Wim Sturkenboom
Polishing naf's code
Code:
/* Get a line of text. */
fgets( buffer, 127, stdin );
You need to leave space for the string terminator.
|
Sorry Wim, you are incorrect here.
From the man page for fgets:
Code:
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s.
Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after
the last character in the buffer.
From MSDN .NET for fgets:
Code:
The fgets function reads a string from the input stream argument and stores it in string. fgets reads characters from the current stream position to and including the first newline character, to the end of the stream, or until the number of characters read is equal to n – 1, whichever comes first. The result stored in string is appended with a null character. The newline character, if read, is included in the string.
And, the most official source 'The C Programming Language', 2nd ed. by Brian W. Kernighan and Dennis M. Ritchie, pg 164:
Code:
The standard libarary provides an input routine fgets that is similiar to the getline function that we have used in earlier chapters:
char *fgets( char *line, int maxline, FILE *fp )
fgets reas the next input line (including the newline) from file fp into the character array line; at most maxline - 1 characters will be read. The resulting line is terminated with '\0'. Normally fgets reutrns line; on end of file or error it returns NULL. (Our getline returns the line length, which is a more useful value; zero means end of file.)
This means if you try giving an input of 500 characters, only 127 will be stored and a '\0' (null character for C string termination) is append on the 128th spot (i.e., buffer[127] = '\0').
Side note, I highly recommend the book just mentioned.