C语言 在 C 中读取单个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14419954/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:05:38  来源:igfitidea点击:

Reading a single character in C

cscanf

提问by g3d

I'm trying to read a character from the console (inside a while loop). But it reads more than once.

我正在尝试从控制台读取一个字符(在 while 循环内)。但它读了不止一次。

Input:

输入:

a

Output:

输出:

char : a  char : char : '

Code:

代码:

while(..)
{
    char in;
    scanf("%c",&in);
}

How can i read only 'a'?

我怎么能只读“a”?

回答by P.P

scanf("%c",&in);

leaves a newline which is consumed in the next iteration.

留下一个在下一次迭代中使用的换行符。

Change it to:

将其更改为:

scanf(" %c",&in); // Notice the whitespace in the format string

which tells scanf to ignore whitespaces.

它告诉 scanf 忽略空格。

OR

或者

scanf(" %c",&in);
getchar(); // To consume the newline 

回答by Douglas

To read just one char, use getcharinstead:

要仅读取一个字符,请改用getchar

int c = getchar();
if (c != EOF)
  printf("%c\n", c);

回答by Manolis Ragkousis

in scanf("%c",&in);you could add after %ca newline character \nin order to absorb the extra characters

scanf("%c",&in);你可以之后添加%c一个换行符\n,以吸收多余的字符

scanf("%c\n",&in);

回答by umsee

you could always use char a = fgetc (stdin);. Unconventional, but works just like getchar().

你总是可以使用char a = fgetc (stdin);. 非常规,但就像getchar().

回答by Cocoo Wang

you can do like this.

你可以这样做。

char *ar;
int i=0;
char c;
while((c=getchar()!=EOF)
   ar[i++]=c;
ar[i]='##代码##';

in this way ,you create a string,but actually it's a char array.

通过这种方式,您创建了一个字符串,但实际上它是一个字符数组。