【问题标题】:Using getchar() when initial user input is "\n" C当初始用户输入为 "\n" C 时使用 getchar()
【发布时间】:2015-10-21 05:31:17
【问题描述】:

当使用 getchar() 方法将字符值设置为指定的用户输入时,用户可能会决定不输入任何内容,但仍按回车键。有没有办法检查字符值是否为“\n”?

// for example:

printf("input y/n\n"); 
char inp; 

// the user hits enter before entering any value
inp = getchar();
getchar();

while (inp != 'y' && inp != 'n') {
    inp = getchar(); 
    getchar(); 
}

if (inp == 'y') {
    printf("+\n"); 
} else {
    printf("-\n"); 
}

示例输入/输出

案例 1
'输入'
yy
结果: +

案例 2
'输入'
是的
是的
yy
结果: +

案例 3
'输入'
是的
'输入'
y
结果: +

有人愿意解释这些案例吗?作为一个 c 新手,但在 java 方面相对有经验,我很想了解 getchar() 的用途和逻辑。

【问题讨论】:

  • 比较你读到的字符和'\n'?另请注意,getchar 返回一个 int(这实际上很重要)。
  • 您的案例 3 似乎与您的代码实际执行的操作不一致。我希望序列ENTERyENTERy 留在while 循环中。
  • 有没有办法检查字符值是否为“\n”?。这是简单的部分。您只需使用if ( inp == '\n' )。你的问题是:当你遇到这种情况时你想做什么?你还没有解释。
  • @R Sahu 谢谢,检查字符值 = '\n' 是否解决了问题

标签: c getchar


【解决方案1】:

请删除第二个 getchar()

// the user hits enter before entering any value
inp = getchar();
//getchar();  // this getchar() is not needed

也在

 while (inp != 'y' && inp != 'n') {
    inp = getchar();
    //  getchar(); // this getchar() is not needed
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多