c - 使用 atoi 解析 csv 文件

标签 c csv atoi

我正在编写一个程序来解析具有以下格式的 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/

相关文章:

c++ - 找到可能的最大内存分配

c - 如何使用 TDM64-GCC 工具链执行标准 GCC "configure"脚本?

python - 如何在 python 中将 csv 转换为 json?

c - IOCCC 1986/wall.c - 为什么 TCC 在处理早期 C 代码方面击败了 GCC?

字符串剥离后的 Python 不需要的空行

mysql - 使用命令行修剪 csv 文件

c - 数组值发生变化

c - 为什么字符串到 int 的转换在第一个索引时不打印数字 0

c - C 中负数的环礁值

c - 链接列表未正确链接