#include "stdio.h"
int main(void)
{
int order, nextp, N=3;
char cont;
nextp = 0;
printf("\nShould we continue (y or n): ");
scanf("%c", &cont);
if (cont != 'y') return;
for(; nextp < N; nextp++)
{
printf("Enter order number: ");
scanf("%d", &order);
printf("you have entered %d\n", order);
printf("okay now continue with cont\n");
printf("enter cont y or n: ");
scanf("%c", &cont);
if (cont != 'y')
{
printf("\nnot equal to y\n");
break;
}
printf("after intepreting t[0]");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出看起来像这样
Should we continue (y or n): y
Enter order number: 45
you have entered 45
okay now continue with cont
enter cont y or n:
not equal to y
Run Code Online (Sandbox Code Playgroud)
第二个输入被跳过了.为什么?
由于stdin中已经存在换行符,这种情况正在发生.使用
scanf(" %c", &cont);
Run Code Online (Sandbox Code Playgroud)
代替
scanf("%c", &cont);
Run Code Online (Sandbox Code Playgroud)
注意%c之前的一个空格.
这就是为什么scanf通常不首选字符输入。上次输入后还有一个回车符。
例如,如果您要getchar()在订单输入后添加 a,您的问题就会得到解决,但这不是干净的代码。您还可以通过替换为cont != 'y'来明确地看到这一点cont != '\n'。
相反,使用getchar()您的所有输入并检查 \n
| 归档时间: |
|
| 查看次数: |
7586 次 |
| 最近记录: |