在洛谷上需要多使用两次 scanf 吃掉回车

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

exlporer @ 2020-04-09 22:56:19

求助,输入 数字位数 在洛谷上后需要两次 scanf() 把回车字符吃掉,但在我的机器上不用

先上代码

#include <iostream>
#include <string>
#include <stdio.h>
#define DEBUG
using namespace std;
const string n[5][10]= {
    {"XXX","..X","XXX","XXX","X.X","XXX","XXX","XXX","XXX","XXX"},
    {"X.X","..X","..X","..X","X.X","X..","X..","..X","X.X","X.X"},
    {"X.X","..X","XXX","XXX","XXX","XXX","XXX","..X","XXX","XXX"},
    {"X.X","..X","X..","..X","..X","..X","X.X","..X","X.X","..X"},
    {"XXX","..X","XXX","XXX","..X","XXX","XXX","..X","XXX","XXX"}
};
const string blink=".";
int main() {
    int num[101],k;
    char tmp;
    scanf("%d",&k);
    //下面的两句在我机器上加了会出错,但不加在洛谷上运行时错误
#ifdef DEBUG
    scanf("%c",&tmp);
    scanf("%c",&tmp);
#endif
    for(int i=-1; i<k; i++) {
        scanf("%c",&tmp);
        num[i]=tmp-'0';
    }
    //分别输出每一排
    for(int i=0; i<5; i++) {
        for(int j=0; j<k; j++) {
            /* printf("%s",n[i][num[j]].c_str()); */
            cout<<n[i][num[j]].c_str();
            if(j<k-1)
                /* printf("%s",blink.c_str()); */
                cout<<blink.c_str();
        }
        cout<<endl;
    }
    return 0;
}

在我的机器上

不加:

 $ cat test.txt | ./a.out
XXX...X.XXX.XXX.X.X.XXX.XXX.XXX.XXX.XXX
X.X...X...X...X.X.X.X...X.....X.X.X.X.X
X.X...X.XXX.XXX.XXX.XXX.XXX...X.XXX.XXX
X.X...X.X.....X...X...X.X.X...X.X.X...X
XXX...X.XXX.XXX...X.XXX.XXX...X.XXX.XXX
[ 10:40PM ]  [ pc@DESKTOP-3T7K257:~/C++ ]

加的话

 $ cat test.txt | ./a.out
XXX.XXX.X.X.XXX.XXX.XXX.XXX.XXX.[1]    12754 done                              cat test.txt | 
       12755 segmentation fault (core dumped)  ./a.out
[ 10:38PM ]  [ pc@DESKTOP-3T7K257:~/C++ ]
 $ cat test.txt          
10
0123456789
[ 10:39PM ]  [ pc@DESKTOP-3T7K257:~/C++ ]

如果是手动输入,打完零我需要按两次回车

g++版本

 $ g++ --version            
g++ (Arch Linux 9.3.0-1) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

请问是我的写法有问题还是编译环境的问题?我觉得按理说输入数字后回车就已经没了的。


by FCBM71 @ 2020-04-09 22:57:06

换行符问题了解一下


by 离散小波变换° @ 2020-04-09 22:57:32

大概是\r\n的问题……

好像因为有的数据在\rm Windows下造,而洛谷在\rm Linux下测,然后就有可能出锅。

通用的解决方法还是手写字符/字符串输入


by chenxinyang2006 @ 2020-04-09 23:03:15

换行符问题挺谔谔的,建议使用scanf %s


by exlporer @ 2020-04-09 23:05:48

@exlporer

...
#endif
    scanf("%c",&tmp);
    for(int i=0; i<k; i++) {
...

还有这里,忘说了,在我机器上设成 0 也需要这样写。为什么会需要额外处理回车? \n 不是在scanf("%d",&k)的时候就被扔掉了吗?


by exlporer @ 2020-04-09 23:14:31

已经了解,多谢各位。


by jyttoby @ 2020-04-09 23:15:12

话说你们都不知道 scanf(" %c", &c) 的吗(注意空格)
效果和你们想的可能不大一样哦


by Terrible @ 2020-04-09 23:15:53

char c=0;
while(c<'0')c=getchar();

可以吃掉无意义的内容。


|