The problem of extra char's in the input buffer, sounds spot on, and is a VERY common problem, since we can't see exactly what the input buffer holds. Consider these two snippets of code:
Code:
#include <stdio.h>
int main(void) {
char choice = 'a';
int n = 0;
while (choice != 'q') {
printf("Enter a letter (or q to quit) : ");
scanf("%c", &choice);
printf("You entered %c, and n now equals %d\n",choice, n++);
}
return 0;
}
Run that, and watch what the value of n becomes, as it loops around. It should show your choice of letter, and 0,1,2,3, etc., but it won't. It will skip your choice sometimes, just like your program is doing, and the reason is that the newline char ('\n'), is being read from the input buffer, as a char, sometimes. (The n is there just to show you that the loop is indeed executing -- but your choice is being "skipped".
Now try this, which fixes the problem:
Code:
#include <stdio.h>
int main(void) {
char choice = 'a';
int n = 0;
while (choice != 'q') {
printf("Enter a letter (or q to quit) : ");
scanf("%c ", &choice); //note the space now, right after the %c - that handles the char immediately after your char
printf("You entered %c, and n now equals %d\n",choice, n++); //effectively discarding the troublesome newline, from the input buffer
}
return 0;
}
//Another way of doing the same thing:
#include <stdio.h>
int main(void) {
char choice = 'a';
int n = 0;
while (choice != 'q') {
printf("Enter a letter (or q to quit) : ");
scanf("%c", &choice);
getchar(); //pulls the newline char from the input buffer, one getchar() pulls one char only.
printf("You entered %c, and n now equals %d\n",choice, n++);
}
return 0;
}
For this problem, a change of compilers won't matter. The input buffer is YOUR responsibility, in C.