我正在做一本书中的练习,Head First C。我仔细检查了我的代码是否与书中的相同,并且我正在仔细按照书中的步骤进行操作。
C 文件应该采用 gps 数据并将其格式化为 JSON 样式。
#include <stdio.h>
int main() {
float latitude;
float longitude;
char info[40];
int started = 0;
puts("data=[");
while (scanf("%f, %f, %39[^\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;
}
首先这本书让我们输入数据,向我们展示它看起来是多么乏味和糟糕的格式,然后我们学习重定向标准输入以读取逗号分隔的数据文件,如下所示:
$ ./geo2json < gpsdata.csv
我在网上找不到源文件,所以我从书中的 pdf 复制/粘贴以创建 csv 文件。
gpsdata.csv and gpsdata.txt
42.363400,-71.098465,Speed = 21
42.363327,-71.097588,Speed = 23
42.363255,-71.096710,Speed = 17
42.363182,-71.095833,Speed = 22
42.363110,-71.094955,Speed = 14
42.363037,-71.094078,Speed = 16
42.362965,-71.093201,Speed = 18
42.362892,-71.092323,Speed = 22
42.362820,-71.091446,Speed = 17
42.362747,-71.090569,Speed = 23
42.362675,-71.089691,Speed = 14
42.362602,-71.088814,Speed = 19
42.362530,-71.087936,Speed = 16
42.362457,-71.087059,Speed = 16
42.362385,-71.086182,Speed = 21
发生了奇怪的事情,所以我通过这些行删除然后重新输入换行符,以防有一些隐藏的格式。我尝试将文件类型从 .csv 更改为 .txt。两者都没有改变。当我输入数据时,这种奇怪并没有发生。
它应该看起来如何:
它实际上看起来如何。请注意最后一行的不同之处。顺便说一句,有时纬度中的“l”会出现在最后一行。
login:~/programming/cfiles> ./geo2json < gpsdata.csv
data=[
'}, itude: 42.363400, longitude: -71.098465, info: 'Speed = 21
'}, itude: 42.363327, longitude: -71.097588, info: 'Speed = 23
'}, itude: 42.363255, longitude: -71.096710, info: 'Speed = 17
'}, itude: 42.363182, longitude: -71.095833, info: 'Speed = 22
'}, itude: 42.363110, longitude: -71.094955, info: 'Speed = 14
'}, itude: 42.363037, longitude: -71.094078, info: 'Speed = 16
'}, itude: 42.362965, longitude: -71.093201, info: 'Speed = 18
'}, itude: 42.362892, longitude: -71.092323, info: 'Speed = 22
'}, itude: 42.362820, longitude: -71.091446, info: 'Speed = 17
'}, itude: 42.362747, longitude: -71.090569, info: 'Speed = 23
'}, itude: 42.362675, longitude: -71.089691, info: 'Speed = 14
'}, itude: 42.362602, longitude: -71.088814, info: 'Speed = 19
'}, itude: 42.362530, longitude: -71.087936, info: 'Speed = 16
'}, itude: 42.362457, longitude: -71.087059, info: 'Speed = 16
'}atitude: 42.362385, longitude: -71.086182, info: 'Speed = 21
]
我查看了在线勘误表,没有看到任何关于此的内容。我使用的是 Cygwin,但后来尝试了 linux,两者的结果相同。
任何帮助或见解将不胜感激!