Originally Posted by
Salem
I see somone determined to learn that using scanf() with any degree of safety is a painful experience
I think you've got the message now caroundw5h
Code:
char buff[BUFSIZ];
while ( fgets( buff, BUFSIZ, stdin ) != NULL ) {
// use sscanf() on buff. If it contains junk just complain and
// go round again. fgets() will get a new line with no unpleasant
// aftertaste of unflushed garbage characters.
}
Yes, fgets() is safe and clean for the purpose (getting information from the user). Just keep in mind that the trailing '\n' is placed into the destination buffer when there is room enough. If the input is greater than the given size, the trailing '\n' is missing.
The ususal trick to manage it is :
Code:
fgets (buf, ...);
{
/* search the '\n' */
char *p = strchr (buf, '\n');
if (p != NULL)
{
/* found : kill it. */
*p = 0;
}
else
{
/* not found : error handling */
/* one option is to flush the stream
* (ignore the extra characters)
*/
int c;
while ((c = fgetc (stream)) != '\n' && c != EOF)
{
}
}
}
Of course, you are not going to add all that stuff each time you use fgets(). This is the reason why it is recommended to build your own reusable 'getline' (or whatever) function, based on this code.
For example:
Code:
char *getline (char *buf, size_t size, FILE *stream);
that returns buf (ok) or NULL (error)
or
Code:
int getline (char *buf, size_t size, FILE *stream);
that returns 0 (ok) or different meaningful error values...