我正在编写一个程序来解析具有以下格式的 csv 文件:
hotdog,10,2,1.5
bun,10,2,0.5
代码应该去除文件的每一行,而现在我只是尝试打印值以确保格式正确。我的问题是正确解释数字数据 - 而不是在 csv 文件中打印整数值,程序正在打印零。该程序正确解析了 csv 中每条记录的第一个字段,所以我认为问题与我的 atoi 格式有关。这是我编写的代码:
char buffer[512]; //512 byte buffer holds the 10 food item names
char* currentLine = buffer; //a temporary pointer to hold the current line read from the csv file
FILE* fp = fopen("inventory.csv", "rw"); //open the inventory.csv file with read and write capabilities.
int i = 0; //counter
while(fgets(currentLine, 1024, fp) != NULL){
printf("%s\n", strtok(currentLine, ",")); //get first field. Should be the food name.
printf("%d\t", atoi(strtok(currentLine, ","))); //get second field. Should be stock amount
printf("%d\t", atoi(strtok(currentLine, ","))); //get third field.
printf("%f\n", atof(strtok(currentLine, ","))); //get forth field.
i++;
}
fclose(fp);
按原样运行会产生以下输出:
hotdog
0 0 0.000000
bun
0 0 0.000000
我的 atoi 格式有问题吗?
最佳答案
查看 strtok 的文档,例如: http://www.cplusplus.com/reference/cstring/strtok/
只有第一次调用需要缓冲区。 后续调用应传递空指针以检索以下 token 。
关于c - 使用 atoi 解析 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22287916/