C语言 如何在 C 中对单个字符执行 scanf
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13542055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do scanf for single char in C
提问by Yuval
In C:
I'm trying to get char from the user with scanfand when I run it the program don't wait for the user to type anything...
在 C 中:我试图从用户那里获取字符scanf,当我运行它时,程序不等待用户输入任何内容......
This is the code:
这是代码:
char ch;
printf("Enter one char");
scanf("%c", &ch);
printf("%c\n",ch);
Why is not working?
为什么不工作?
回答by John Bode
The %cconversion 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 scanfcall will consume it immediately.
该%c转换符不会自动跳过任何前导空格,所以如果有输入流中的寄生换行符(从以前的条目,例如)的scanf调用将立即使用它。
One way around the problem is to put a blank space before the conversion specifier in the format string:
解决此问题的一种方法是在格式字符串中的转换说明符之前放置一个空格:
scanf(" %c", &c);
The blank in the format string tells scanfto skip leading whitespace, and the first non-whitespace character will be read with the %cconversion specifier.
格式字符串中的空白告诉scanf跳过前导空格,第一个非空格字符将使用%c转换说明符读取。
回答by P.P
First of all, avoid scanf(). Using it is not worth the pain.
首先,避免scanf()。使用它不值得痛苦。
See: Why does everyone say not to use scanf? What should I use instead?
Using a whitespace character in scanf()would ignore any number of whitespace characters left in the input stream, what if you need to read more inputs? Consider:
使用空格字符 inscanf()会忽略输入流中剩余的任意数量的空格字符,如果您需要读取更多输入怎么办?考虑:
#include <stdio.h>
int main(void)
{
char ch1, ch2;
scanf("%c", &ch1); /* Leaves the newline in the input */
scanf(" %c", &ch2); /* The leading whitespace ensures it's the
previous newline is ignored */
printf("ch1: %c, ch2: %c\n", ch1, ch2);
/* All good so far */
char ch3;
scanf("%c", &ch3); /* Doesn't read input due to the same problem */
printf("ch3: %c\n", ch3);
return 0;
}
While the 3rd scanf() can be fixed in the same way using a leading whitespace, it's not always going to that simple as above.
Another major problem is, scanf()will not discard any input in the input stream if it doesn't match the format. For example, if you input abcfor an intsuch as: scanf("%d", &int_var);then abcwill have to read and discarded. Consider:
虽然第三个 scanf() 可以使用前导空格以相同的方式修复,但并不总是像上面那样简单。另一个主要问题是,scanf()如果输入流中的任何输入与格式不匹配,则不会丢弃它。例如,如果你输入abc一个int如:scanf("%d", &int_var);然后abc将有读取和丢弃。考虑:
#include <stdio.h>
int main(void)
{
int i;
while(1) {
if (scanf("%d", &i) != 1) { /* Input "abc" */
printf("Invalid input. Try again\n");
} else {
break;
}
}
printf("Int read: %d\n", i);
return 0;
}
Another common problem is mixing scanf()and fgets(). Consider:
另一个常见问题是混合scanf()和fgets()。考虑:
#include <stdio.h>
int main(void)
{
int age;
char name[256];
printf("Input your age:");
scanf("%d", &age); /* Input 10 */
printf("Input your full name [firstname lastname]");
fgets(name, sizeof name, stdin); /* Doesn't read! */
return 0;
}
The call to fgets()doesn't wait for input because the newline left by the previous scanf() call is read and fgets() terminates input reading when it encounters a newline.
调用fgets()不会等待输入,因为读取了前一个 scanf() 调用留下的换行符,并且 fgets() 在遇到换行符时终止输入读取。
There are many other similar problems associated with scanf(). That's why it's generally recommended to avoid it.
还有许多其他类似的问题与scanf(). 这就是为什么通常建议避免它。
So, what's the alternative? Use fgets()function instead in the following fashion to read a single character:
那么,有什么替代方案呢?fgets()以以下方式使用function 来读取单个字符:
#include <stdio.h>
int main(void)
{
char line[256];
char ch;
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
ch = line[0];
printf("Character read: %c\n", ch);
return 0;
}
One detail to be aware of when using fgets()will read in the newline character if there's enough room in the inut buffer. If it's not desirable then you can remove it:
fgets()如果 inut 缓冲区中有足够的空间,则使用时要注意的一个细节将读取换行符。如果不需要,则可以将其删除:
char line[256];
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
line[strcpsn(line, "\n")] = 0; /* removes the trailing newline, if present */
回答by Sanberk
Here is a similiar thing that I would like to share,
这里有一个类似的东西,我想分享,
while you're working on Visual Studio you could get an error like:
在 Visual Studio 上工作时,您可能会收到如下错误:
'scanf': function or variable may be unsafe. Consider using
scanf_sinstead. To disable deprecation, use_CRT_SECURE_NO_WARNINGS
'scanf':函数或变量可能不安全。考虑
scanf_s改用。要禁用弃用,请使用_CRT_SECURE_NO_WARNINGS
To prevent this, you should write it in the following format
为防止这种情况,您应该按照以下格式编写它
A single character may be read as follows:
单个字符可以读作如下:
char c;
scanf_s("%c", &c, 1);
When multiple characters for non-null terminated strings are read, integers are used as the width specification and the buffer size.
当读取非空终止字符串的多个字符时,整数用作宽度规范和缓冲区大小。
char c[4];
scanf_s("%4c", &c, _countof(c));
回答by Kaushik
neither fgets nor getchar works to solve the problem. the only workaround is keeping a space before %c while using scanf scanf(" %c",ch); // will only work
fgets 和 getchar 都不能解决问题。唯一的解决方法是在使用 scanf scanf(" %c",ch); 时在 %c 之前保留一个空格;// 只会工作
In the follwing fgets also not work..
在以下 fgets 也不起作用..
char line[256];
char ch;
int i;
printf("Enter a num : ");
scanf("%d",&i);
printf("Enter a char : ");
if (fgets(line, sizeof line, stdin) == NULL) {
printf("Input error.\n");
exit(1);
}
ch = line[0];
printf("Character read: %c\n", ch);
回答by Praveen samuel
This works for me try it out
这对我有用 试试看
int main(){
char c;
scanf(" %c",&c);
printf("%c",c);
return 0;
}
回答by Praveen samuel
try using getchar(); instead
尝试使用 getchar(); 反而
syntax:
句法:
void main() {
char ch;
ch = getchar();
}
回答by SYLVIO CAVALCANTI
Before the scanf put fflush(stdin);to clear buffer.
在 scanf 之前放fflush(stdin);清缓冲区。
回答by Shahid Nawaz
Provides a space before %c conversion specifier so that compiler will ignore white spaces. The program may be written as below:
在 %c 转换说明符之前提供一个空格,以便编译器将忽略空格。程序可以写成如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char ch;
printf("Enter one char");
scanf(" %c", &ch); /*Space is given before %c*/
printf("%c\n",ch);
return 0;
}
回答by POTATO
Use string instead of charlike
使用字符串而不是char像
char c[10];
scanf ("%s", c);
I belive it works nice.
我相信它很好用。
回答by AL Maruf
You have to use a valid variable. chis not a valid variable for this program. Use char Aaa;
您必须使用有效的变量。ch不是此程序的有效变量。使用char Aaa;
char aaa;
scanf("%c",&Aaa);
Tested and it works.
经测试,它有效。

