I'm trying to do this loop in C, where you would press enter and be in it and you either press 0 to exit or 3 to continue in it. But somehow the Switch commands are no being activated. Note that there is a different messages on each of them that is supposed to differentiate them from the other outcomes. Can someone help me understand the problem with this code?`Note: the code is obviously within int main().
int I = 1;
printf("Press enter to start the loop...");
getchar();
do
{
printf("\nYou are in a LOOP. Would you like to stay in it, or leave it? \nPress 0 to leave the loop or press 3 to stay in it: ");
scanf_s("%d", &I);
getchar();
switch (I)
{
case'3':
printf("\nYou are STILL inside the LOOP. Press 0 to leave it or press 3 to stay in it: ");
getchar();
break;
case'0':
printf("\nExiting the LOOP...");
break;
default:
printf("\nPlease, enter a valid command...: ");
if (scanf_s("%d", &I) != 3 || scanf_s("%d", &I) != 0);
{
fflush(stdin);
}
break;
}
while (I != 0);
printf("\nCongratulations! You are OUT of the LOOP!");
As others have pointed out, you are reading in an integer with scanf_s(), but comparing against a character literal inside the switch statement.
switch'3':
should be written as switch 3:
(using an integer literal instead). Same goes for the 0 case.
Also, your example is missing a curly brace }
before while(I != 0);
.
It is also worth mentioning that scanf_s() "returns the number of fields successfully converted and assigned" (from https://msdn.microsoft.com/en-us/library/w40768et.aspx ). That is, your scanf_s() call in the default switch case will only ever return 0 or 1 when reading in a single integer (or EOF on error).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.