Reading single-character
define this function for cutting every following '\n'
#include <stdio.h> void drain_stdin () { int c; do { c = fgetc(stdin); } while (c != EOF && c != '\n'); }
example use with scanf() for a char. now the while-loop isn't executed twice while ENTER
ing a character.
int main() { char x = 1; while (x != '0') { printf( "Enter a char or '0' to exit: " ); scanf( "%c", &x ); drain_stdin(); printf( "The input was: %c\n\n\n", x); } return 0; }
Reading string
same problem sollution as above, but now with a string. this one avoids the dangerous gets() function and cut away the input-following '\n' read-in by fgets()
size_t len; char buffer[1024]; fgets(buffer, sizeof(buffer), stdin); len = strlen(buffer); if(buffer[len - 1] == '\n') buffer[len - 1] = 0;
Links
Both sollutions are provided here: