为什么不的getchar()等我preSS scanf函数后进入()? [英] Why doesn't getchar() wait for me to press enter after scanf()?
问题描述
我学习C和我使用的getchar()来停止命令窗口,以便我能看到练习在做,但它只是不工作。继承人的例子:
的#include<&stdio.h中GT;诠释的main()
{
int值;
的printf(1选项1. \\ N2选项2 \\ N3选项3 \\ N4退出\\ n \\ n请一个选项:。);
scanf函数(%d个,&安培;值);
开关(值)
{
情况1:
的printf(您选择的选项1);
打破;
案例2:
的printf(您选择的选项2);
打破;
案例3:
的printf(您选择的选项3);
打破;
情况4:
的printf(再见);
打破;
默认:
的printf(那不是一个选项);
打破;
}
的getchar();
返回0;
}
这是输出:
- 选项1。
- 选项2
- 选项3。
- 退出。
请选择一个选项:1。
您所选择的选项1。
进程返回0(为0x0)执行时间:3.453小号
preSS任意键继续。
块引用>为什么它不等待输入的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.\n2. option 2.\n3. option 3.\n4. Exit\n\nMake 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 usingsscanf()
to scan the string.这篇关于为什么不的getchar()等我preSS scanf函数后进入()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!