c - 使用 while 循环在 C 中切换

标签 c while-loop switch-statement

我是 C 编程的新手。我写了一个简单的 switch case 但它没有按预期执行。谁能告诉我这里出了什么问题??

#include <stdio.h>

int main() {
    int i;
    char yes;
    bool flag = true;

    while(flag) {
        printf("Enter the value");
        scanf("%d",&i);

        switch(i) {
            case 1:
                printf("Hi");                       
                break;

            case 2:
                printf("Hello");                        
                break;                      
        }

        printf("Enter Y or N to continue");
        scanf("%c",&yes);
        if (yes == 'N') {
            flag = false;       
        }
    }

    return 0;
}

我期望的结果是:

Enter the Value
1
Hi
Enter Y or N to continue
Y
Enter the Value
2
Hello
Enter Y or N to continue
N

但我得到的结果是:

Enter the value 1
HiEnter Y or N to continueEnter the value N
HiEnter Y or N to continue

最佳答案

当您点击 Enter 时输入第一个数字后,scanf从输入流中读取除 Enter 产生的换行符以外的所有数字字符打。换行符不是数字的一部分。它留在输入流中,未读,等待其他人读取。

下一个scanf("%c",&yes);发现了挂起的换行符,它没有等待就读取了它。 %c格式说明符不会跳过输入中的空格,它只会读取它看到的第一个字符。

替换你的 scanf

scanf(" %c",&yes);

让它跳过空格。这样它就会忽略待处理的换行符并实际等待您输入内容。

关于c - 使用 while 循环在 C 中切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27006993/

相关文章:

c - 为什么缓冲区位于 main() 本地,然后无法显式关闭流是一个错误?

c - 为什么 getchar() 不能正常工作?

java - while 循环输入?

java - 我可以将 return 语句放在 switch 语句中吗?

networking - 为什么无线接入点工作在链路层

c - 疯狂的宏hack,用于处理线程取消和清理处理程序的问题

名为 "AB"的结构可以包含 AB 数组吗?

c - 在C中: How do I terminate while loop when comparing string output to external file

java - 如何在java Scanner类的while循环中使用OR条件?

php - Switch Case 或 if else if 哪个更快更好?