繁体   English   中英

用C语言的switch case执行while循环不起作用

[英]Do while loop with switch case in C language not working

我正在尝试在C语言中执行此循环,您将按Enter并进入其中,然后按0退出或按3继续。 但是不知何故,Switch命令没有被激活。 请注意,每条消息上都有一条不同的消息,应该将它们与其他结果区分开。 有人可以帮我理解这段代码的问题吗?`注意:该代码显然在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!");

正如其他人指出的那样,您正在使用scanf_s()读取整数,但是将其与switch语句中的字符文字进行比较。
switch'3':应写为switch 3:改用整数文字)。 0情况也是如此。

同样,您的示例在while(I != 0);之前缺少花括号} while(I != 0);

还值得一提的是scanf_s()“返回成功转换和分配的字段数”(来自https://msdn.microsoft.com/zh-cn/library/w40768et.aspx )。 也就是说,在默认开关情况下,您的scanf_s()调用仅在读取单个整数(错误时返回EOF)时才返回0或1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM