我是个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;
}
我期望的结果是:
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
发布于 2014-11-19 00:48:15
当您在键入第一个数字后按Enter
时,scanf
将从输入流中读取除Enter
命中所产生的换行符以外的所有数字字符。换行符不是数字的一部分。它留在输入流中,未读,等待其他人读取它。
下一个scanf("%c",&yes);
发现挂起的换行符,它不需要等待就读取它。%c
格式说明符不会跳过输入中的空格,它只读取它看到的第一个字符。
将您的scanf
替换为
scanf(" %c",&yes);
使其跳过空格。这样,它将忽略挂起的换行符,并实际等待您输入某些内容。
发布于 2014-11-19 00:47:47
在所有printf
中,您需要在末尾添加\n
。
有关用法的示例,请参阅此处:printf
发布于 2014-11-19 00:49:41
这对你来说应该是可行的:
(您忘记了printf
语句中的所有'\n'
,并在char scanf
语句中添加了一个space
)
#include <stdio.h>
int main() {
int i;
char yes;
int flag = 1;
while(flag) {
printf("Enter the value\n");
scanf("%d",&i);
switch(i){
case 1:
printf("Hi\n");
break;
case 2:
printf("Hello\n");
break;
}
printf("Enter Y or N to continue\n");
scanf(" %c", &yes);
if (yes == 'N')
flag = 0;
}
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
https://stackoverflow.com/questions/27006993
复制