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

基于C++实现文本文件读取与结构体容器操作的问题求助

CSV数据解析与结构体存储实现

数据示例

item,price,qty,ordno,trdno
abc,54,2,123,32
xyz,34,2,345,21

字段类型定义

item: string (char[])
price,qty (int)
ordno (long long)
trdno (int)

需求要求

  • 为上述字段定义结构体
  • 使用vector存储该结构体的多个实例
  • 实现以下功能:
    1. 读取文本文件
    2. 逐行读取并分割字段值
    3. 初始化结构体对象
    4. 将结构体对象添加至容器
    5. 文件读取完成后,遍历容器并按「序号、ordno、trdno、price、qty、item」格式输出每个元素的值

原代码问题分析

你的代码存在以下关键问题:

  1. 结构体类型不匹配:price定义为double(需求为int),order_no定义为int(需求为long long),不符合字段类型要求
  2. 冗余输入与读取冲突:开头的cin>>n完全多余,且会导致后续getline读取到缓冲区残留的换行符,破坏文件读取逻辑
  3. 字段分割逻辑错误:仅对文件最后一行进行分割,未逐行处理所有数据,也未跳过表头行
  4. 未实现核心需求:没有用vector存储结构体实例,也未按指定格式输出结果

正确实现代码

#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <string>

// 严格匹配字段类型定义结构体
struct OrderItem {
    std::string item;
    int price;
    int qty;
    long long ordno;
    int trdno;
};

// 按指定分隔符分割字符串的工具函数
std::vector<std::string> split(const std::string& s, char delimiter) {
    std::vector<std::string> tokens;
    std::string token;
    std::istringstream tokenStream(s);
    while (std::getline(tokenStream, token, delimiter)) {
        tokens.push_back(token);
    }
    return tokens;
}

int main() {
    std::vector<OrderItem> items;
    std::ifstream read("input.txt");
    
    // 检查文件是否成功打开
    if (!read.is_open()) {
        std::cerr << "无法打开文件 input.txt" << std::endl;
        return 1;
    }

    std::string line;
    // 跳过表头行
    std::getline(read, line);

    // 逐行读取并处理数据
    while (std::getline(read, line)) {
        std::vector<std::string> fields = split(line, ',');
        // 校验数据字段数量是否正确
        if (fields.size() != 5) {
            std::cerr << "数据行格式错误:" << line << std::endl;
            continue;
        }

        // 初始化结构体并转换字段类型
        OrderItem currItem;
        currItem.item = fields[0];
        currItem.price = std::stoi(fields[1]);
        currItem.qty = std::stoi(fields[2]);
        currItem.ordno = std::stoll(fields[3]);
        currItem.trdno = std::stoi(fields[4]);

        items.push_back(currItem);
    }

    read.close();

    // 按要求格式输出结果
    std::cout << "序号、ordno、trdno、price、qty、item" << std::endl;
    for (size_t i = 0; i < items.size(); ++i) {
        const auto& item = items[i];
        std::cout << i+1 << "、" 
                  << item.ordno << "、" 
                  << item.trdno << "、" 
                  << item.price << "、" 
                  << item.qty << "、" 
                  << item.item << std::endl;
    }

    return 0;
}

代码说明

  1. 结构体定义:严格匹配字段类型,将结构体命名为OrderItem避免与字段item混淆
  2. 分割函数:封装split函数实现按逗号分割字符串,提升代码复用性
  3. 文件读取:先跳过表头行,逐行处理数据,添加格式校验避免错误数据干扰
  4. 类型转换:使用stoi/stoll将字符串转换为对应数值类型,确保类型正确
  5. 输出逻辑:遍历vector容器,按指定格式输出,序号从1开始计数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:35:19