You need to enable JavaScript to run this app. C语言实现从文本文件读取字符串存入结构体数组的问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

C语言实现从文本文件读取字符串存入结构体数组的问题咨询

读取TXT内容到结构体数组的实现方案

现存代码核心错误

  • 字符串传参错误:结构体成员pin/first/last均为字符数组,fscanf读取%s格式字符串时直接传入数组首地址即可,即users[i].pin,无需额外加[j]索引——后者是取字符数组第j位元素的地址,会导致内容写入非法内存位置。
  • 数组下标起始错误:C语言数组下标从0开始,原代码初始化i=1会直接跳过userList[0]元素。
  • 缺少循环逻辑:仅调用一次fscanf无法读取文件内所有行,需循环判断读取结果直至文件末尾。
  • 冗余temp变量无效:测试用users.txt每行仅3个字段,无第四个内容需要存储;且%s格式符会自动跳过换行符、空格等空白字符,strcmp(temp, "\n")的判断逻辑完全不生效。
  • 无读取长度限制:未限制fscanf读取的字符串长度,存在缓冲区溢出风险,需针对数组成员大小指定读取宽度(如pin[5]对应%4s)。

修正后可运行代码

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

struct userStruct {
    char pin[5];
    char first[26];
    char last[26];
};

int main()
{
    struct userStruct userList[10] = {0}; // 初始化数组清零,避免残留垃圾值
    struct userStruct *users = userList;  // 数组名本身为首地址,无需额外取址
    FILE *filePtr;
    int userCount = 0; // 记录有效用户数,防止越界写入

    filePtr = fopen("users.txt", "r");
    if (filePtr == NULL) {
        printf("Unable to open users.txt\n");
        return 1;
    }

    // 循环读取:最多存10个用户,且每次成功读取3个字段才推进计数
    while (userCount < 10 && 
           fscanf(filePtr, "%4s %25s %25s", 
                  users[userCount].pin, 
                  users[userCount].first, 
                  users[userCount].last) == 3) {
        printf("PIN %s| First %s| Last %s|\n", 
               users[userCount].pin, 
               users[userCount].first, 
               users[userCount].last);
        userCount++;
    }

    fclose(filePtr);
    return 0;
}

运行效果

针对提供的测试users.txt内容,输出为:

PIN 1234| First John| Last Smith|
PIN 5678| First Barry| Last Cool|

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 08:36:07