Use fgets() for everything.
So for example.
int Menu()
{
char buff[BUFSIZ];
int choice = 0; /* menu choice value */
/* with the following loop we force the user to choose
* on of the 3 valid answers: 1, 2, or 3
*/
do {
fprintf(stdout, "Please choose one of the following:\n"
"1. do1 \n"
"2. do2 \n"
"3. do3 \n");
fgets( buff, sizeof buff, stdin );
if ( sscanf( buff, "%d", &choice ) != 1 ) {
printf( "I asked for a number!\n" );
}
} while ( choice != 1 && choice != 2 && choice != 3);
return choice;
}
This also fixes your "what if they type the wrong thing" problem as well.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
>>it isn't the best thing to mix io functions from different families
but scanf() and fgets() are of the same family of functions, all declared in stdio.h But it is NOT good to use scanf() for string input because it can (potentially) corrupt and possibly crash your program if you enter a string that is longer then the buffer size you want to hold it.
Ancient Dragon
Retired & Loving It
30,041 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,341
scanf() uses the bare minimum of characters necessary to perform the conversion, and leaves the first character which cannot be converted on the input stream.
So if you type in
42\n
and scan that with "%d", then 42 will be used and \n will be left.
Now you come along with fgets(), and boom, first character is \n, and it's "thank you and good night from fgets()".
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439