All formatted input functions stop at whitespace, both in C and C++.
Your scanf()s should also have safeguards on how many characters can be input. For example:
1 2
|
char name[20];
scanf( "%19s", name ); /* There's only room to read 19 characters + '\0' */
|
Switching to
gets() was a good idea, but the problem was that you had used
scanf() some time before. Consider the following input:
5\nyoroshite kudasai\n
Notice the newlines in there? If you use
scanf() to read "5", the first newline is
not eaten up, but remains. So the input now looks like:
\nyoroshite kudasai\n
When you now try to
fgets() the string, it thinks that you are done because of that newline. You have to get rid of it first.
In C++ there's a routine to do that, but in C you have to write your own.
1 2 3 4 5
|
void ignoref( FILE* f, size_t n, char c )
{
while (n-- && (fgetc( f ) != c))
;
}
|
User input will always end with an Enter Key press, meaning a newline, so it is good to keep those out of the way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int age;
char name[20];
char* p;
printf( "What is your age? " );
fflush( stdout );
scanf( "%d", &age );
ignoref( stdin, (-1), '\n' ); /* get rid of the Enter Key that the user just pressed */
printf( "What is your name? " );
fflush( stdout );
fgets( name, 20, stdin );
/* Of course, now you must get rid of the newline in your string. */
p = strchr( name, '\n' );
if (p) *p = '\0';
else ignoref( stdin, (-1), '\n' ); /* but if it wasn't in the string then you must still get it from input */
|
Another way of handling input is typically to
fgets() the user's input entirely, then
sscanf() the stuff you want out of it.
Sorry it isn't any simpler. It really is a very obnoxious way to handle input, but that's the way it has always been in C and C++. It might be worth your time writing a function which gets the thing you want (like an integer) and cleans up the newline. Then you only need to call your special function and you'll know that input is synchronized with newlines.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
int get_int( FILE* stream, int default_value )
{
int result;
if (!fscanf( stream, "%d", &result )) result = default_value;
ignoref( stream, (-1), '\n' );
return result;
}
int main()
{
int n;
puts( "How many times?" );
n = get_int( stdin, 0 );
while (n--)
puts( "Yeah!" );
return 0;
}
|
Good luck!