问题描述
在C:
我试图从用户那里获取煤焦与 scanf函数
键,当我运行它的程序不等待用户输入什么...
In C:I'm trying to get char from the user with scanf
and when I run it the program don't wait for the user to type anything...
这是code:
char ch;
printf("Enter one char");
scanf("%c", &ch);
printf("%c\n",ch);
为什么不工作?
推荐答案
的%C
转换符不会自动跳过任何前导空格,所以如果有一个流浪换行符在输入流(从previous条目,例如)在 scanf函数
通话将立即使用它。
The %c
conversion specifier won't automatically skip any leading whitespace, so if there's a stray newline in the input stream (from a previous entry, for example) the scanf
call will consume it immediately.
解决此问题的方法之一是在格式字符串转换说明符之前放一个空格:
One way around the problem is to put a blank space before the conversion specifier in the format string:
scanf(" %c", &c);
在格式字符串中的空白告诉 scanf函数
跳过的空白,以及第一个非空白字符将与%C读
转换说明。
The blank in the format string tells scanf
to skip leading whitespace, and the first non-whitespace character will be read with the %c
conversion specifier.
这篇关于如何在C单个字符做scanf函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!