One of the things I was trying to point out, and which was included in the code posted by SourceCode, was the handling of the case in which the input exceeds the buffer size. Text remains in stdin. Not handling it may be a bug, much like the issue with '\n' and scanf.
Code:
#include <stdio.h>
#include <string.h>
char *foo(char *buffer, size_t size, const char *prompt)
{
if ( buffer != NULL )
{
if ( prompt != NULL )
{
fputs(prompt, stdout);
fflush(stdout);
}
if ( fgets(buffer, size, stdin) != NULL )
{
char *newline = strchr(buffer, '\n');
if ( newline != NULL )
{
*newline = '\0';
}
#if 0
else
{
while ( getchar() != '\n' ) { /* consume leftovers */ }
}
#endif
}
}
return buffer;
}
int main(void)
{
char buffer[10] = "";
while ( *buffer != '0' )
{
printf("buffer = \"%s\"\n", foo(buffer, sizeof(buffer), "prompt: "));
}
return 0;
}
/* sample input/output #if 0
prompt: This text is really, really, really long. Bigger than the buffer size.
buffer = "This text"
prompt: buffer = " is reall"
prompt: buffer = "y, really"
prompt: buffer = ", really "
prompt: buffer = "long. Big"
prompt: buffer = "ger than "
prompt: buffer = "the buffe"
prompt: buffer = "r size."
prompt: 0
buffer = "0"
*/
/* sample input/output #if 1
prompt: This text is really, really, really long. Bigger than the buffer size.
buffer = "This text"
prompt: 0
buffer = "0"
*/
Several searches show that I've left this out a number of times, so I thought it was worth menthioning.