C char无法在if..else中工作

时间:2014-04-12 01:45:33

标签: c if-statement char scanf

当我运行程序时,无论我为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;
}

3 个答案:

答案 0 :(得分:0)

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

scanf_s(" %c", &shape);

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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