lea*_*ner 0 c while-loop switch-statement
我是C编程的新手.我写了一个简单的开关案例,但没有按预期执行.有人可以告诉我这里有什么问题吗?
#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;
}
Run Code Online (Sandbox Code Playgroud)
我期待的结果是:
Enter the Value
1
Hi
Enter Y or N to continue
Y
Enter the Value
2
Hello
Enter Y or N to continue
N
Run Code Online (Sandbox Code Playgroud)
但我得到的结果是:
Enter the value 1
HiEnter Y or N to continueEnter the value N
HiEnter Y or N to continue
Run Code Online (Sandbox Code Playgroud)
当你打Enter的第一个号码输入后,scanf读取输入流中的所有数字字符,除了由所产生的换行符Enter命中.换行符不是数字的一部分.它留在输入流中,未读,等待其他人阅读.
接下来scanf("%c",&yes);发现了挂起的换行字符,它无需等待即可读取.该%c格式说明不跳过输入的空白,它只是读取它看到的第一个字符.
更换你scanf用
scanf(" %c",&yes);
Run Code Online (Sandbox Code Playgroud)
使它跳过空格.这样它就会忽略那个挂起的换行符并且实际上等着你输入一些内容.