The
std::cin and
getline() stuff are all C++ entities. You won't get them to work without compiling with a C++ compiler. I don't recommend mixing C and C++ files blithely.
helios hit it right on:
fgets() reads everything up to and
including the terminating '\n'. You can tell whether or not you have read the entire line of input by checking for that '\n' at the end of the line.
scanf() reads only that which it is asked, and no more. So not only will you leave an extra '\n' in the input, your user could have left other stuff there also.
In C, I always recommend that you not use the standard input functions directly, but that you build something a little more powerful on top of them.
This is such a common need that you might want to check out the
GNU Readline Library. You won't be disappointed.
http://tiswww.case.edu/php/chet/readline/rltop.html
If you can't use it (for whatever reason), you can roll your own input very simply:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
char* simple_readline( const char* prompt, unsigned block_size )
{
char* result; /* The malloc()ed string to return */
char* block; /* Each chunk of the string */
char* ok; /* Used to check for input errors */
unsigned size; /* The current size of the entire string */
unsigned n; /* strlen() of the last block */
if (!block_size) block_size = 50;
if (prompt) printf( "%s", prompt );
block = result = (char*)malloc( size = block_size );
if (!result) return NULL;
*result = '\0';
for (;;)
{
/* Get the next block of characters until EOL */
ok = fgets( block, block_size, stdin );
if (!ok) break;
/* If we found EOL we are done */
n = strlen( block );
if (block[ n -1 ] == '\n') break;
/* Else add more memory and try again */
ok = (char*)realloc( result, size += block_size );
if (!ok) break;
block = ok +block -result -1;
result = ok;
}
if (!(*result))
{
free( result );
result = NULL;
}
return result;
}
| |
Now use it exclusively for input.
1 2 3 4 5 6 7 8 9 10
|
char* users_input;
printf( "%s", "What is your name? " );
users_input = simple_readline( NULL, 0 );
if (!users_input) return complaint( "fooey!" );
printf( "Hello %s!\n", users_input );
free( users_input );
users_input = NULL;
| |
Etc. To read numbers and the like, use the
strtox() functions on the string.
1 2 3 4 5 6 7 8 9 10
|
double age;
char* users_input = simple_readline( "How old are you? ", 0 );
if (!users_input) return complaint( "fooey again!" );
age = strtod( users_input, NULL ); /* don't forget to actually do some error checking here (I didn't) */
free( users_input );
users_input = NULL;
printf( "You are %f dog-years old.\n", age / 7.0 );
| |
Hope this helps.