为什么 getchar() 在 scanf() 之后不等我按回车键? [英] Why doesn't getchar() wait for me to press enter after scanf()?
问题描述
我正在学习 C,我正在使用getchar()"来停止命令窗口,所以我可以看到正在做的练习,但它不起作用.这是一个示例:
#include int main(){整数值;printf("1.选项1.
2.选项2.
3.选项3.
4.退出
做一个选项:");scanf("%d", &value);开关(值){情况1:printf("你选择了选项1.");休息;案例2:printf("你选择了选项2.");休息;案例3:printf("您选择了选项 3.");休息;案例4:printf("再见");休息;默认:printf("那不是一个选项");休息;}获取字符();返回0;}
这是输出:
<块引用>- 选项 1.
- 选项 2.
- 选项 3.
- 退出.
做一个选择:1
您选择了选项 1.
进程返回 0 (0x0) 执行时间:3.453 s
按任意键继续.
为什么不等待getchar()"的输入?
你的 scanf 只吃了数字,而不是尾随的换行符.在 %d 后面放一个换行符或空格会给你带来相反的问题,读得太远.
这就是人们不喜欢 scanf 的原因.
我建议阅读实际行(使用 fgets(3)
),然后使用 sscanf()
扫描字符串.
I am learning C and I'm using "getchar()" to stop the command windows so I can see the exercises am doing but it just doesn't work. heres a sample:
#include <stdio.h>
int main()
{
int value;
printf("1. option 1.
2. option 2.
3. option 3.
4. Exit
Make an option: ");
scanf("%d", &value);
switch (value)
{
case 1:
printf("you selected the option 1.");
break;
case 2:
printf("you selected the option 2.");
break;
case 3:
printf("you selected the option 3.");
break;
case 4:
printf("goodbye");
break;
default:
printf("thats not an option");
break;
}
getchar();
return 0;
}
this is the output:
- option 1.
- option 2.
- option 3.
- Exit.
Make an option: 1
you selected the option 1.
Process returned 0 (0x0) execution time : 3.453 s
Press any key to continue.
Why doesn't it wait for the input of "getchar()"?
Your scanf only ate the number but not the trailing newline. Putting a newline or white space after the %d will then give you the opposite problem, reading too far.
This is why people don't like scanf.
I would suggest reading an actual line (use fgets(3)
) and then using sscanf()
to scan the string.
这篇关于为什么 getchar() 在 scanf() 之后不等我按回车键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!