This question already has answers here:
scanf() leaves the new line char in the buffer
                                
                                    (4个答案)
                                
                        
                                4年前关闭。
            
                    
这是代码

int
read_data(void){
    char type;
    double x_val,y_val,noise_val;
    while (scanf("%c %lf %lf %lf",&type,&x_val,&y_val,&noise_val)==4){
        printf("%c %lf %lf %lf",type,x_val,y_val,noise_val);
    }
    return 0;
}


输入是

N 501.0 7501.0 80.0
N 1001.0 5001.0 90.0
N 3501.0 7501.0 130.0
N 5001.0 2001.0 85.0


当我编译为test < testing.txt后输入时,它仅打印第一行。

但是,如果我删除while循环并继续添加更多的scanfs并打印,则这是输出。

N 501.000000 7501.000000 80.000000

 501.000000 7501.000000 80.000000
N 1001.000000 5001.000000 90.000000

 1001.000000 5001.000000 90.000000
N 3501.000000 7501.000000 130.000000

 3501.000000 7501.000000 130.000000
N 5001.000000 2001.000000 85.000000

 5001.000000 2001.000000 85.000000


怎么了?

最佳答案

问题在于scanf调用不会在第一行之后读取换行符,它仍将在输入缓冲区中,因此,下次您调用scanf时,"%c"格式将读取该换行符,然后尝试读取字符N作为浮点数,这将失败并且循环将退出。

一个简单的解决方案是使用fgets读取行,然后使用sscanf解析已读取的行。

10-07 19:08
查看更多