c - 将 CSV 文本文件中的值输入到数组中

标签 c arrays csv

出于某种原因,我的程序在第一个 while 循环中出错了,但我真的不明白为什么。昨天我正在为 stdin 使用标准重定向输入,我假设打开一个文件基本上是同一件事。为什么它现在不起作用?

这是我保存为“.csv”的文本文件,我正在打开它:

热狗, 10, 2, 1.50
包子, 10, 2, 0.50
汉堡, 100, 10, 2.00

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int i = 0, j = 0;
    char command[25], str[100];
    int quantity[100], limit[100];
    double cost[100];
    char *item[100];
    char *token, *ptr;

    FILE *fp = fopen("inventory.csv", "rw");
    if(fp == NULL)
    {
        perror ("Error opening file");
    }

    //testing to see if program gets until here, then tries to copy data from CSV to arrays
    while(fgets(str, 100, fp) != NULL)
    {
        token = strtok (str,",");
        ptr = strdup(token);
        item[i] = ptr;
        sscanf (token, "%s", item[i]);
        token = strtok (NULL,",");
        sscanf (token, "%d", &quantity[i]);
        token = strtok (NULL,",");
        sscanf (token, "%d", &limit[i]);
        token = strtok (NULL,"\n");
        sscanf (token, "%lf", &cost[i]);
        i++;
    }

    printf("hey");

    for(j=0;j<i;j++)
        {
            printf("%s, %d, %d, %lf\n", item[j], quantity[j], limit[j], cost[j]);
        }

    strcpy(command, argv[1]);

    if(strcmp(command,"list") == 0)
    {
        for(j=0;j<i;j++)
        {
            printf("%s, %d, %d, %lf\n", item[j], quantity[j], limit[j], cost[j]);
        }
    }
    else
    {
        printf("wtf hello");
    }
    return 0;
}

最佳答案

在下面的语句中对于sscanf条目的地址应该给出

sscanf (token, "%d", &quantity[i]);

sscanf (token, "%d", &limit[i]);

sscanf (token, "%lf", &cost[i]);

关于c - 将 CSV 文本文件中的值输入到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22299050/

相关文章:

mysql - 将csv导入mysql时日期字段值错误

以下需要解释的 C 指针输出

java - java将所有数组元素重新初始化为零

php - 从数组中删除在指定键上具有重复值的元素

javascript - 使用 JavaScript 将数据从 .csv 文件导入到 HTML 表

python - 来自 csv python 的分层 JSON

c++ - 如何将 char 数组中的值与另一个 char 进行比较

iphone - 如何从 iPhone 中后台进程的名称访问(复制/修改)特定的 appfiledirectory?

c - 如何从 C 运行外部程序并解析其输出?

java - 在 List<Integer> 上使用 set 方法会导致不支持的操作异常