You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中将CSV数据解析至结构体时出现类型转换错误的解决方案咨询

Fixing Your CSV-to-Struct Parsing Issues

Let's break down your code's key issues and fix them step by step:

1. Correct Your Struct Definitions

Your structs have two critical flaws that break data storage:

  • In struct Course, char *course_name[50]; declares an array of 50 char pointers, but you only need a single pointer to reference the course names from dataArr. Simplify it to:
    struct Course {
        char *course_name;
        int grade;
    };
    
  • In struct Student, struct Course; is an incomplete declaration—it doesn't create a member to hold the student's courses. Since each student has 6 courses, declare an array of struct Course:
    struct Student {
        char *name;
        struct Course courses[6];
        int index;
    };
    
    (If you want to avoid dynamic memory later, you can swap char *name; with char name[50]; instead.)

2. Fix the Uninitialized sName Pointer

You’re using char *sName; without allocating memory for it. Calling strcpy(sName, token); writes to random memory, causing undefined behavior. Fix this either by:

  • Using a fixed-size array: char sName[50];
  • Or dynamically allocating memory: sName = malloc(strlen(token) + 1); (remember to free this later!)

3. Fix Struct Initialization Syntax

Your original struct initialization line had invalid syntax—you can’t nest course data that way, and you were accidentally assigning an int to a pointer member (from your original flawed course_name array). Instead:

  • Create a struct Student instance (or array of instances) before parsing
  • Assign the student’s name first
  • Fill each Course in the courses array as you parse grades

Revised Working Code

Here’s the full fixed code that correctly parses your CSV into structs:

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

// Fixed Struct Definitions
struct Course {
    char *course_name;
    int grade;
};

struct Student {
    char *name;
    struct Course courses[6];
    int index;
};

char *dataArr[6] = {"Intro to Programming","Databases","Computer Architecture","Ethics in Computer Science","Advanced Programming","Puzzles and Problem Solving"};

void Import_and_Print() {
    printf("\nImporting files and storing data in structs...\n\n");
    FILE * fp;
    char * line = NULL;
    size_t len = 0;
    ssize_t read;
    int student_index = 0;
    const char s[2] = ",";
    char *token;

    fp = fopen("Sample2.csv", "r");
    if (fp == NULL)
        exit(EXIT_FAILURE);

    // Skip the header line
    read = getline(&line, &len, fp);

    // Array to store students (adjust size based on your CSV)
    struct Student students[3];

    while ((read = getline(&line, &len, fp)) != -1 && student_index < 3) {
        // Make a copy of the line so strtok doesn't modify the original
        char *csvData = strdup(line);
        token = strtok(csvData, s);

        // Allocate memory for student name and copy it
        students[student_index].name = malloc(strlen(token) + 1);
        strcpy(students[student_index].name, token);
        printf("Student name: %s\n", students[student_index].name);

        token = strtok(NULL, s);
        int course_idx = 0;
        while (token != NULL && course_idx < 6) {
            int in_grade = atoi(token);
            // Assign course name and grade to the struct
            students[student_index].courses[course_idx].course_name = dataArr[course_idx];
            students[student_index].courses[course_idx].grade = in_grade;
            printf("Course: %s\tGrade: %i\n", dataArr[course_idx], in_grade);

            token = strtok(NULL, s);
            course_idx++;
        }

        students[student_index].index = student_index;
        student_index++;
        free(csvData); // Clean up the copied line
        printf("\n\n");
    }

    // Verify stored data works correctly
    printf("Verifying stored struct data:\n");
    for (int i = 0; i < student_index; i++) {
        printf("Student %d: %s\n", i, students[i].name);
        for (int j = 0; j < 6; j++) {
            printf("  %s: %d\n", students[i].courses[j].course_name, students[i].courses[j].grade);
        }
    }

    // Clean up dynamic memory
    for (int i = 0; i < student_index; i++) {
        free(students[i].name);
    }
    free(line);
    fclose(fp);
}

int main() {
    Import_and_Print();
    return 0;
}

Key Changes Explained

  • Struct Fixes: Properly defined the course array in Student and simplified Course to hold a single pointer for course names.
  • Memory Safety: Used malloc for student names (and freed them later to avoid leaks) and strdup to protect the original input line from strtok modifications.
  • Parsing Logic: Separated student name parsing from grade parsing, then filled each course in the student's array one by one.
  • Verification: Added a section to print stored struct data so you can confirm the data is being saved correctly.

内容的提问来源于stack exchange,提问作者Clauric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 04:07:46