【问题标题】:Scanning a char in for method doesn't work like expected在 for 方法中扫描 char 不像预期的那样工作
【发布时间】:2021-09-21 18:04:08
【问题描述】:

该程序的目标是根据用户如何将它们放在一起扫描一系列 X、1、2,然后显示他放入了多少 X。

由于某种原因,在我放了 8 X/1/2 之后(按 ENTER 8 次,因为我一个一个放了它们) 无论我如何输入数字,它都会显示数字 15。

我的问题是,当 for 设置为 i=1; i<=TOTOSIZE; i++ 时,为什么它会在 8 个 ENTER 后停止 TOTOSIZE = 15

为什么它总是显示数字 15 而不是它应该做的。

#include <stdio.h>
#define TOTOSIZE 15

int main()
{
    int d = 0, i;
    char score;
    
    for (i = 1; i <= TOTOSIZE; i++)
    {
        scanf_s("%c", &score);
        if (score == 'X');
        {
            d++;
        }
        _flushall();
    }

    printf("%d", d);

    return 0;
}

【问题讨论】:

标签: c input


【解决方案1】:

您的代码的以下部分中有两项可能会导致跳过问题。 (另一个答案也解决了一个问题。)

for (i = 1; i <= TOTOSIZE; i++)
{
    //scanf_s("%c", &score);//using scanf to read char like this may skip due to newlines
    scanf_s(" %c", &score);//leading space in format specifier will consume space, including newline.
    //       ^ 
    if (score == 'X');
    {            //  ^ should not be there.  It nullifies the false result of test
        d++;
    }
    _flushall();
}

leading space reference

【讨论】:

    【解决方案2】:

    我可能没有正确理解您,但据我了解,您输入了 15 个不同的字符,每个字符为 1、2 或 X,并计算输入了多少个 X。如果这是正确的,那么您的问题似乎是 if 语句后面的分号。这段代码可以工作 -

    #include <stdio.h>
    #define TOTOSIZE 15
    
    int main()
    {
        int d = 0, i;
        char score;
        
        for (i = 1; i <= TOTOSIZE; i++)
        {
            scanf_s("%c", &score);
            if (score == 'X')
            {
                d++;
            }
            _flushall();
        }
    
        printf("%d", d);
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      相关资源
      最近更新 更多