The Program runs the last chosen case when you input a char.
This is because when scanf("%d", &x);
failed it did not updated the variable x
. x
still remembers the last chosen good number.
Check the standard 7.21.6.4 The scanf function.
You can read about behaviour of scanf
here.
On success, the scanf
returns the number of items successfully read. This count can match the expected number of readings or fewer, even zero, if a matching failure happens. In the case of an input failure before any data could be successfully read, EOF is returned.
Knowing that you can check the return value of scanf
and make appropriate decision. In the program below, bad scanf
input is treated as case 4:
and program ends:
#include <stdio.h>
int main(){
int x;
do{
printf("Input a number:\n");
if(scanf("%d", &x) != 1){
printf("Error - END.\n");
break;
}
switch(x){
case 1: printf("A\n\n");
break;
case 2: printf("B\n\n");
break;
case 3: printf("C\n\n");
break;
case 4: printf("End\n");
break;
default: printf("Invalid.\n");
}
}while(x!=4);
return 0;
}
Output:
Input a number:
0
Invalid.
Input a number:
1
A
Input a number:
2
B
Input a number:
3
C
Input a number:
N
Error - END.
Edit:
If OP requires program to continue to run after user bad input, that requires more work.
The naive approach is to replace the break
with continue
.
That will not work! Any character that does not match the format string causes scanf
to stop scanning and leaves the invalid character still in the buffer!
To continue we have to flush the invalid character out of the buffer.
The modified program is given below:
#include <stdio.h>
#include <ctype.h>
int main(){
int x;
char c;
int error = 0;
do{
c = '0';
if(!error)
printf("Input a number:\n");
else
error = 0;
if(scanf("%d", &x) != 1)
{
printf("No letters! Input a number:\n");
do
{
c = getchar();
}
while (!isdigit(c));
ungetc(c, stdin);
error = 1;
continue;
}
switch(x){
case 1: printf("A\n\n");
break;
case 2: printf("B\n\n");
break;
case 3: printf("C\n\n");
break;
case 4: printf("End\n");
break;
default: printf("Invalid.\n");
}
}while(x!=4);
return 0;
}
Output:
Input a number:
1
A
Input a number:
X
No letters! Input a number:
1
A
Input a number:
4
End