scanf读取错误的char

时间:2015-10-29 12:09:42

标签: c scanf

我需要在C中编写一个程序,让用户选择绘制一个矩形方块或打印他制作的板子,但每次在第一次输入形状后,程序就会像输入无效字符一样

printf("please make you decision R-rectangle, S-square, E-end\n");
scanf("%c", &decision);
do
{
    if (decision == 'R') {
        printf("you chose rectangle! please enter the X start position, Y start position, hieght and width\n");
        scanf("%d %d %d %d", &rectMat[0][rectCounter], &rectMat[1][rectCounter], &rectMat[2][rectCounter], &rectMat[3][rectCounter]);
        if (rectCounter + 1 < MAX_RECT)
        {
            if (checkRECT(rectMat[0][rectCounter], rectMat[1][rectCounter], rectMat[2][rectCounter], rectMat[3][rectCounter], areaMat) == 1)
            {
                drawRECT(rectMat[0][rectCounter], rectMat[1][rectCounter], rectMat[2][rectCounter], rectMat[3][rectCounter], areaMat);
                rectCounter++;
            }
            else
            {
                printf("we couldn't fit you rectangle\n");
            }
        }
        else
        {
            printf("you have too many rectangles\n");
        }
    }

    if (decision == 'S')
    {
        printf("you chose square! please enter the X start position, Y start position and size of the side\n");
        scanf("%d  %d  %d", &sqrMat[0][rectCounter], &sqrMat[1][rectCounter], &sqrMat[2][rectCounter]);
        if (sqrCounter<MAX_SQR)
        {
            if (checkSQR(sqrMat[0][rectCounter], sqrMat[1][rectCounter], sqrMat[2][rectCounter],areaMat)==1)
            {
                drawSQR(sqrMat[0][rectCounter], sqrMat[1][rectCounter], sqrMat[2][rectCounter], areaMat);
                sqrCounter++;
            }
            else
            {
                printf("we couldn't fit your square\n");
            }
        }
        else
        {
            printf("you have too many sqaures\n");
        }
    }
    if (decision == 'P')
    {
        printArea(areaMat);
    }
    if (decision != 'E'&& decision != 'P'&& decision != 'S'&& decision != 'R')
    {
        printf("invalid entry\n");
    }
    printf("please make you decision R-rectangle, S-square, E-end\n");
    scanf("%c", &decision);
} while (decision != 'E');

2 个答案:

答案 0 :(得分:4)

当您使用"%c"格式读取字符时,它将读取输入缓冲区中的下一个字符,它不会跳过任何空白区域。当使用scanf读取任何内容时,您输入的用于将输入发送到程序的换行也将被发送,并在输入结束后添加为空白字符。大多数格式会跳过前导空格(例如"%d"格式),但"%c""%["格式不会。

当读取字符时,几乎总是建议跳过前导空格,这是通过在格式之前添加空格来完成的,例如。

scanf(" %c", &decision);
//     ^
//     |
// Note space here

另请注意,大写和小写字母之间存在差异。 'R' != 'r'。检查大写和小写字母,或使用toupper(或tolower)进行转换。

答案 1 :(得分:1)

你最好使用getc() scanf()的instad,因为你无论如何都期待一个字符