疑惑:getchar();与scanf("\n");的不同结果

P5730 【深基5.例10】显示屏

Kazuma_124 @ 2023-11-14 20:51:29

代码如下(C语言):

#include <stdio.h>
const char example[10][5][4] = {
    {"XXX","X.X","X.X","X.X","XXX"},
    {"..X","..X","..X","..X","..X"},
    {"XXX","..X","XXX","X..","XXX"},
    {"XXX","..X","XXX","..X","XXX"},
    {"X.X","X.X","XXX","..X","..X"},
    {"XXX","X..","XXX","..X","XXX"},
    {"XXX","X..","XXX","X.X","XXX"},
    {"XXX","..X","..X","..X","..X"},
    {"XXX","X.X","XXX","X.X","XXX"},
    {"XXX","X.X","XXX","..X","XXX"}
};
char num[102];
char out[5][100 * 4];
int main() {
    int n;
    /* 
    scanf("%d", &n);
    getchar();
    这样是WA
    报错是:read (ASCII 0), expected ..
    */

    //换成下面这样就对了
    scanf("%d\n",&n);
    /*
    scanf("%d",&n);
    scanf("\n");
    这样也可以
    */

    gets(num);

    for (int i = 0; i<5; i++) {
        for (int j = 0; j < n; j++) {
            out[i][0+j*4] = example[(num[j]) - '0'][i][0];
            out[i][1+j*4] = example[(num[j]) - '0'][i][1];
            out[i][2+j*4] = example[(num[j]) - '0'][i][2];
            if (j != n - 1) {
                out[i][3+j*4] = '.';
            }
        }
    }

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 4 * n - 1; j++) {
            printf("%c", out[i][j]);
        }
        printf("\n");
    }
}
  • 这样是WA.

    scanf("%d", &n);
    getchar();

    报错是:read (ASCII 0), expected ..

  • 换成下面这样就对了

    scanf("%d\n",&n);

    请问为什么会出现这种情况,getchar()和scanf("\n")有什么不同吗?


by 70CentsApple @ 2023-11-14 20:53:42

如果数据是 Windows 系统造的话,结尾会多一个 \r


by chaynflow @ 2023-11-14 20:57:58

@tjr0513 反了吧


by tjr0513 @ 2023-11-14 21:00:39

@chy2011 对哦,抱歉


|