【问题标题】:C char not working in if..else [duplicate]C char 在 if..else 中不起作用 [重复]
【发布时间】:2014-05-26 08:21:19
【问题描述】:

当我运行程序时,无论我为shape 输入什么,都会执行最后的else 语句。

#include <stdio.h>

int main(void)
{
    char shape = 'a';
    printf("What shape do you want?\nEnter 's' for a Square, 'b' for a Box, 't' for a Triangle\n");

    while (shape != 's' && shape != 'b' && shape != 't')
    {
        scanf_s(" %c", &shape);

        if (shape == 's')
        {
            printf("You entered %c", shape);
        }

        else if (shape == 'b')
        {
            printf("You entered %c", shape);
        }

        else if (shape == 't')
        {
            printf("you entered %c", shape);
        }

        else
        {
            printf("Please enter 's' 'b' or 't'");
        }
    }
    return 0;
}

【问题讨论】:

标签: c if-statement char scanf


【解决方案1】:

scanf_s 需要您要读取的字符数(因此是_s)。试试scanf(" %c", &amp;shape, 1)

【讨论】:

    【解决方案2】:

    您在参数 1 中似乎有一个空格字符。

    scanf_s(" %c", &shape);
    

    【讨论】:

      【解决方案3】:

      scanf_s(" %c", &amp;shape); 替换为scanf_s(" %c", &amp;shape, (size_t)1);scanf(" %c", &amp;shape);。 您没有提供足够的论据。

      【讨论】:

        猜你喜欢
        • 2020-04-29
        • 2015-09-04
        • 1970-01-01
        • 2014-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多