阅读在C单个字符 [英] Reading a single character in C

查看:140
本文介绍了阅读在C单个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读从控制台的字符(在while循环中)。但它读取一次以上。

输入:

  A

输出:

 字符:一个字符:字符:'

code:

 而(..)
{
    在烧焦;
    scanf函数(%C,&安培;中);
}

我怎么只能读'一'?


解决方案

  scanf函数(%C,&安培;中);

离开其在下次迭代消耗换行。

将其更改为:

  scanf函数(%C,&安培;中); //请注意格式字符串中的空白

它告诉scanf函数忽略空格。

  scanf函数(%C,&安培;中);
的getchar(); //要消耗换行符

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

Input:

a

Output:

char : a  char : char : '

Code:

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

How can i read only 'a'?

解决方案

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.

OR

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

这篇关于阅读在C单个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆