scanf()
takes the input that matches the format string, returning the number of characters consumed. Any character that doesn't match the format causes it to stop scanning and leaves the invalid character still in the buffer.
To let the strange not happen, the possible ways to fix this issues:
- Use
fgets()
to take the string and compare - recommended.
- Use
fflush(stdin)
- not recommended.
Aside: Use int confirm
rather than using char
for it. The reason is:
A char is required to accept all values between 0 and 127 (included).
So in common environments it occupies exactly one byte (8 bits). It is
unspecified by the standard whether it is signed (-128 - 127) or
unsigned (0 - 255).
An int is required to be at least a 16 bits signed word, and to accept
all values between -32767 and 32767. That means that an int can accept
all values from a char, be the latter signed or unsigned.
Note: You may use char confirm
when you specifically needs to store characters.
Reference: Difference between char and int when declaring character.
Example 1 (recommended):
#include <stdio.h>
#define MAX_LENGTH 100
int main(void) {
char confirm[MAX_LENGTH];
printf("Enter a valid command (Y/N): ");
fgets(confirm, MAX_LENGTH, stdin); // using fgets() here
while (confirm[0] != 'Y' && confirm[0] != 'y' \
&& confirm[0] != 'N' && confirm[0] != 'n') {
printf("Please enter a valid answer (Y/N): ");
fgets(confirm, MAX_LENGTH, stdin); // using fgets() here
}
return 0;
}
Expected sample output should be:
$ gcc -o prog prog.c; ./prog
Enter a valid command (Y/N): asdf
Please enter a valid answer (Y/N): asdlfasdf asdf a
Please enter a valid answer (Y/N): 234
Please enter a valid answer (Y/N): n
Example 2:
Do something like:
while (...)
{
printf("Please enter a valid answer (Y/N):\n");
fflush(stdin);
scanf(" %c", &confirm);
}
Then you may expect this output:
Do you want to proceed? (Y/N):
d
Please enter a valid answer (Y/N):
asdf
Please enter a valid answer (Y/N):
asdfasd
Please enter a valid answer (Y/N):
n