It's because scanf()'s %c matches newlines as well as ordinary characters. When you tell scanf to read a number and enter "123\n", it takes the "123" and leaves the "\n" for the next scanf to read when looking for a character.
There are lots of ways around this problem. The best is probably to read input as lines with fgets() and then use sscanf() to parse those lines.
Code:
char buffer[BUFSIZ];
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%c", &c);
/* or, with error checking: */
if(!fgets(buffer, sizeof(buffer), stdin);
|| sscanf(buffer, "%c", &c) != 1) {
perror("Error reading stdin");
}
Another way is to simply discard any trailing whitespace between scanf()s. You can do this with a single
or better yet, in case there are multiple newlines or spaces:
Code:
while(getchar() != '\n');
BTW -- this is the C++ forum, and cin and cout should be used in C++ instead of scanf() and printf().