In my C program which is using switch I have problem with my int variable. My code is:
while(1) {
printf("0. END\n1. TRANSLATE\n2. TEST FROM LESSON\n3. RANDOM"
" WORDS TEST\n4. SHOW DICTIONARY\n5. ADD WORD\n"
"6. DELETE WORD\nYOUR CHOICE: ");
scanf("%d",&option);
fflush(stdin);
printf("\n");
switch(option) {
case 0: {
exit(0);
break;
}
case 1: {
system("cls");
translate();
printf("\n");
break;
}
case 2: {
system("cls");
lessons();
printf("\n");
break;
}
case 3: {
randomFromLessons();
printf("\n");
break;
}
case 4: {
system("cls");
allWords();
printf("\n");
break;
}
case 5: {
system("cls");
addWord();
break;
}
case 6: {
system("cls");
deleteWord();
printf("\n");
break;
}
default: {
printf("---------------\n");
printf("WRONG VALUE.\n");
printf("---------------\n\n");
}
}
}
When I type 'd' into option var. it shows default, which is what I want, BUT when I press number 1 which starts method named "translate()" and then get back into main menu and press 'd' again it gets me back into "translate()" instead of showing the default.
When I use char instead of int, there is no problem. So, what exactly is the problem? What keeps happening? What am I doing wrong? Isn't using char in switch the best option overall then?
CodePudding user response:
If you wish to allow text input, you should read the input as a string with fgets
and then convert to integers as needed.
If you only wish to accept numbers, you should check the result of scanf
to see if it succeeded - in this case it will return 1
when successful, in case it managed to read 1 parameter. If not successful, it won't overwrite option
but keep the previous value - that's why you get the behavior you describe.
Furthermore fflush(stdin);
is undefined behavior since fflush
was never meant to be used on input streams. To just discard the line feed character from stdin you can add single getchar()
.
So you could fix the code into something like this:
int result;
while(1)
{
result = scanf("%d",&option);
getchar();
if(result == 1)
break;
else
printf("some error message\n");
}
switch(option)
...