我是 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/