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

结构体赋值遇阻:使用循环与fgets读取课程文件统计CSCI课程数

Hey there! Let's work through this problem together. It sounds like you've got the right idea using a struct and looping with fgets, but hitting a roadblock when assigning data to the struct. Let's break this down into actionable steps with code examples.

First, let's define a sensible class struct that matches the data in your input file. We'll need fields for the course code, name, and credits:

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

typedef struct {
    char code[8];  // Fits "CSCIXXX" + null terminator with room to spare
    char name[50]; // Adjust this size if your course names are longer
    int credits;
} class;

Next, let's walk through the core logic: opening the file, reading each line, checking if it's a CSCI course, populating the struct, and counting the total. The tricky part here is splitting the line correctly since course names have spaces—we can't just use scanf directly because it stops at whitespace.

Here's a complete working example:

int main() {
    FILE *course_file = fopen("your_input_file.txt", "r");
    if (!course_file) {
        perror("Oops, couldn't open the file");
        return 1;
    }

    char line_buffer[100]; // Buffer to hold each full line
    int csci_course_count = 0;
    class current_course;

    while (fgets(line_buffer, sizeof(line_buffer), course_file) != NULL) {
        // Remove the trailing newline that fgets includes
        size_t line_len = strlen(line_buffer);
        if (line_len > 0 && line_buffer[line_len - 1] == '\n') {
            line_buffer[line_len - 1] = '\0';
        }

        // Skip empty lines if any exist
        if (strlen(line_buffer) == 0) continue;

        // Check if this line is a CSCI course
        if (strncmp(line_buffer, "CSCI", 4) == 0) {
            csci_course_count++;

            // Extract the course code (first 6 characters: e.g., CSCI112)
            strncpy(current_course.code, line_buffer, 6);
            current_course.code[6] = '\0'; // Always manually add null terminator!

            // Find the start of the course name (skip the code and following space)
            char *name_start = line_buffer + 7;

            // Find the last space in the line—this separates the name from the credits
            char *credits_pos = strrchr(line_buffer, ' ');
            if (credits_pos != NULL) {
                // Null-terminate the name at that last space
                *credits_pos = '\0';
                // Copy the name to the struct, avoiding buffer overflow
                strncpy(current_course.name, name_start, sizeof(current_course.name) - 1);
                current_course.name[sizeof(current_course.name) - 1] = '\0';

                // Parse the credit value from the end of the line
                current_course.credits = atoi(credits_pos + 1);

                // Optional: Verify the struct was populated correctly
                printf("Processed CSCI Course: %s | %s | %d credits\n",
                       current_course.code, current_course.name, current_course.credits);
            }
        }
    }

    printf("\nTotal CSCI courses counted: %d\n", csci_course_count);
    fclose(course_file);
    return 0;
}

Key Notes to Fix Your Struct Assignment Issues:

  • Always null-terminate strings: When using strncpy, it won't automatically add a \0 if the source string is longer than the destination buffer. Manually adding it prevents garbage data in your struct.
  • Avoid buffer overflow: Use strncpy instead of strcpy and limit the number of characters copied to one less than your struct field's size—this leaves room for the null terminator.
  • Handle spaces in course names: Using strrchr to find the last space in the line lets us split the name from the credits correctly, even when the name has multiple spaces.
  • Error checking: Always verify the file opened successfully—this saves you from head-scratching when the code fails for obvious reasons.

If you were running into issues like garbage characters in your struct fields or incorrect values, these fixes should resolve those problems. Let me know if you hit any other snags!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:20:31