我正在编写一些应从文件中读取CSV数据并将其转换为JSON的代码。我可以使它与简单的值(例如浮点数和整数)一起使用,但对于char src [100],它似乎什么也没打印。我想这与字符串的终止方式有关,但我迷路了。为什么会发生这种情况的任何指导将不胜感激。
/* Takes CSV data as input and converts it to json */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define MAX 80
void die(const char *msg)
{
if(errno)
perror(msg);
else
printf("%s\n", msg);
exit(1);
}
int main(int argc, char *argv[])
{
char src[100];
//char eqid[MAX];
int version;
//char date[MAX];
float latitude;
float longitude;
float magnitude;
float depth;
//int nst;
//char region[MAX];
int started = 0;
puts("data_callback ({");
puts("\"data\": [");
while(scanf("%s,%d,%f,%f,%f,%f", src, &version, &latitude, &longitude, &magnitude, &depth) == 6) {
if(started)
printf(",\n");
else
started = 1;
if((latitude < -90.0) || (latitude > 90.0)) {
die("Latitude out of bounds");
}
else if((longitude < -180.0) || (longitude > 180.0)) {
die("Longitude out of bounds");
}
printf("{\"src:\" %s, \"version\": %d, \"latitude\": %f, \"longitude\": %f, \"magnitude\": %f, \"depth\": %f}", src, version, latitude, longitude, magnitude, depth);
}
puts("\n]})");
return 0;
}
输出:
./convert_to_json
"data": [
然后我粘贴诸如:
10565ch1,1,64.4679,-148.0767,1.3,11.70
最终输出只是一个空行:
"data": [
10565ch1,1,64.4679,-148.0767,1.3,11.70
// should be the json formatted code here
]})
如果仅使用浮点数和整数运行同一程序,我将得到:
{"version": 1, "latitude": 64.467903, "longitude": -148.076706, "magnitude": 1.300000, "depth": 11.700000}
我如何使它与char一起使用? TIA