解析CSV文本行时出错

LuM*_*uMa 2 c csv ansi-c

我无法在C中解析CSV文件.我需要使用该文件中的数据来提交结构.这是我结构的相关部分:

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

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

    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! */
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是什么?

chu*_*ica 5

无法保存到char使用中strcpy().

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

strcpy(info.correct, getLine(line, 4)); /* Crashs! */
Run Code Online (Sandbox Code Playgroud)

使用

info.correct = *getLine(line, 4);
Run Code Online (Sandbox Code Playgroud)

您的编译器应该已经警告过这个.查看编译器设置.

  • @LuMa不清楚是"你的解决方案也不起作用".并且"某种程度上strcpy-operation失败"因为答案应该使用`info.correct =*getLine(line,4);`**而不是**的strcpy(info.correct,getLine(line,4)); (2认同)