为什么我的C程序输出的printf格式奇怪?

3

我的源代码如下:

#include <stdio.h>
int main()
{
    float latitude;
    float longitude;
    char info[80];
    int started = 0;
    puts("data=[");
    while (scanf("%f, %f, %79[^\n]", &latitude, &longitude, info) == 3) {
        if (started)
            printf(",\n");
        else
            started = 1;
        printf("{latitude: %f, longitude: %f, info: '%s'}", latitude, longitude, info);

    }
    puts("\n]");
    return 0;
}

我有一个名为gpsdata.csv的数据文件,内容如下:

42.363400,-71.098465,Speed = 21
42.363327,-71.097588,Speed = 23
42.363255,-71.096710,Speed = 17

我理解

./geo2json < gpsdata.csv
data=[
'},titude: 42.363400, longitude: -71.098465, info: 'Speed = 21
'},titude: 42.363327, longitude: -71.097588, info: 'Speed = 23
{latitude: 42.363255, longitude: -71.096710, info: 'Speed = 17'}
]

看起来是行末覆盖了行首,我做错了什么?

"%79[^\n]" 并不是你想象中的那样。 - Adam Liss
1个回答

6

您的数据文件使用Windows风格的换行符(\r\n;回车加换行符,而不是常规操作系统的\n(换行符))。每次打印回车并将光标移动到行的开头。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接