【问题标题】:Why is the while loop getting repeated twice without letting me scan for the 2nd time, when I enter something different the first time? [duplicate]为什么当我第一次输入不同的内容时,while 循环会重复两次而不让我第二次扫描? [复制]
【发布时间】:2021-03-26 15:33:45
【问题描述】:

当它要求我输入一个字符并且我输入 say 'b' 时,它会执行最后一行,然后与最后一行一起再次执行整个循环,而不执行其间的 scanf 语句。

#include <stdio.h>
void main()
{
    char ch = 'C';

     while( ch != 'A')
        {
            printf("Enter your character\n");
            scanf("%c" ,&ch);
            printf("\nLoop must execute completely\n");
        }
    
    }

【问题讨论】:

  • 您正在输入"b\n"

标签: c while-loop scanf


【解决方案1】:

scanf("%c" ,&ch);

原因:输入某个字符后,按回车(换行符\n),第二次迭代时scanf会读取这个换行符(\n) . %c 格式说明符可以读取空格字符,例如空格、制表符、换行符(换行符)和回车符。

解决方案:将scanf("%c" ,&amp;ch); 更改为scanf(" %c" ,&amp;ch);。在 scanf 中添加尾随空格将读取任何多余的空格字符。

【讨论】:

  • 您的解决方案有效,但我不明白为什么。为什么工作前要加空格?请解释
  • @JoyMajumdar:请阅读:stackoverflow.com/questions/1247989/…
  • @JoyMajumdar 额外的空格告诉scanf 跳过空白字符,它实际上会在读取和存储字符之前跳过任意数量的空白字符。
猜你喜欢
  • 1970-01-01
  • 2017-03-13
  • 2020-04-30
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 2012-11-02
  • 2014-08-06
相关资源
最近更新 更多