【问题标题】:How can we ignore the enter button press as a character in c programming at the time of taking input from user?在接受用户输入时,我们如何在 c 编程中忽略按回车键作为字符?
【发布时间】:2020-11-27 23:45:34
【问题描述】:

看例子:

#include<stdio.h>
int main()
{
    char ch;
    while(scanf("%c", &ch))
    {
        if(ch == 'a' || ch == 'e' || ch == 'i' ||
                ch == 'o' || ch == 'u' || ch == 'A' ||
                ch == 'E' || ch == 'I' || ch == 'O' ||
                ch == 'U')
        {
            printf("It's Vowel\n");
        }
        else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
        {
            printf("It's Consonant\n");
        }
        else
        {
            printf("Wrong Input/ It's not Alphabet\n");
        }
    }
    return 0;
}

编译此示例代码后,当我输入“a”时,输出为“It's Vowel”和“Wrong Input/It's not Alphabet”。我认为这个输出的原因是,编译器把这个字符也把回车作为一个字符。

有没有办法解决这个问题?

【问题讨论】:

  • 添加测试 if (ch == '\n') break; 或者 while(scanf("%c", &amp;ch)) --> while(scanf(" %c", &amp;ch))。检测到'\n' 后,您希望发生什么?

标签: c input while-loop


【解决方案1】:

我认为这个输出的原因是,编译器将字符也作为字符。

接受字符的不是编译器。获取输入是一个运行时操作。当程序已经运行时,编译器的工作就完成了,但除此之外你的猜测是正确的。这是因为scanf() 不使用在第一步按 Enter 生成的换行符。

然后,scanf("%c", &amp;ch)) 在下一次迭代中读取此换行符,并且由于换行符是合法字符,因此它存储在 ch 中。

有没有办法解决这个问题?

使用

while(scanf(" %c", &ch))

而不是

while(scanf("%c", &ch))

注意%c 之前的空格字符 (' ')。这将获取上次迭代中留在stdin 中的废弃换行符。

【讨论】:

  • 非常感谢!!我从您的回答中找到了解决方案。
  • 非常感谢!!我从您的回答中找到了解决方案。
  • @AlamgirHossain 如果您认为这个答案最有帮助或解决了您的问题,请随时accept it。谢谢。
猜你喜欢
  • 2017-06-03
  • 2013-01-18
  • 1970-01-01
  • 2015-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
相关资源
最近更新 更多