2

我无法在 C 中解析 CSV 文件。我需要使用该文件中的数据归档一个结构。这是我的结构的相关部分:

typedef struct Info {
    /* Some strings, integers, etc. */
    char correct; /* This is the value I can't set */
    short int status;
} t_info;

我文件中的一行看起来像xxxxxx;xxxxxxx;xxxxxxx;D;254D是我的问题,见下文)。

    char line[1024]; /* Buffer */
    t_info info;

    fgets(line, sizeof(line), fp);

    strcpy(info.xxxxxx, getLine(line, 1)); /* Works */
    strcpy(info.xxxxxx, getLine(line, 2)); /* Works */
    strcpy(info.xxxxxx, getLine(line, 3)); /* Works */
    strcpy(info.correct, getLine(line, 4)); /* Crashs! */

getLine() 函数取自这篇文章:

const char *getLine(char *line, int num)
{
    const char *tok, *tmp = strdup(line);

    for (tok = strtok(tmp, ";"); tok && *tok; tok = strtok(NULL, ";\n"))
    {
        if (!--num)
            return tok;
    }

    return NULL;
}

我的问题是什么?

4

2 回答 2

5

无法保存成charusing strcpy()

typedef struct Info {
    char correct; /* This is the value I can't set */
} t_info;

strcpy(info.correct, getLine(line, 4)); /* Crashs! */

利用

info.correct = *getLine(line, 4);

您的编译器应该对此提出警告。查看编译器设置。

于 2015-12-20T22:55:12.697 回答
2

解决此问题的最简单方法是获取该行的第一个字符,并将其用于 char。

info.correct = getLine(line, 4)[0];

也许 sscanf 可能更适合您的应用程序(此处为指南)(类似答案)

于 2015-12-20T22:32:39.303 回答