如何用C++读取CSV文件中的单列数据?代码报错求修复
修复CSV读取第一列ID的C++代码异常问题
原代码核心问题分析
- 索引越界异常:
data[rowIdx].push_back(value)直接访问未初始化的vector行——data初始为空,没有任何行元素,通过索引访问会触发内存越界错误。 - 未处理边界情况:未检查文件是否成功打开、文件为空、
find找不到目标列名的场景,会导致程序无预警崩溃。 - 冗余与笔误:重复包含
<string>头文件,注释中存在与需求不符的"computer science"笔误。
修复后的完整代码
#include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include<cstdlib> #include<cstring> using namespace std; int main() { ifstream fin("1.csv"); // 检查文件是否成功打开 if (!fin.is_open()) { cerr << "无法打开文件1.csv" << endl; return 1; } string line; int rowCount = 0; // 统计文件总行数 while (getline(fin, line)) { rowCount++; } vector<vector<string>> data; data.reserve(rowCount); // 预先分配空间,提升效率 fin.clear(); fin.seekg(0, ios::beg); // 将文件指针重置到开头 while (getline(fin, line)) { stringstream ss(line); string value; // 先添加空行到data,避免索引越界 data.push_back(vector<string>()); while (getline(ss, value, ',')) { // 往当前最后一行插入元素 data.back().push_back(value); } } fin.close(); int colNum = -1; const string colName = "ID"; // 处理空文件情况 if (data.empty()) { cerr << "文件内容为空" << endl; return 1; } // 查找ID列的索引 auto it = find(data[0].begin(), data[0].end(), colName); if (it == data[0].end()) { cerr << "未找到名为ID的列" << endl; return 1; } colNum = distance(data[0].begin(), it); // 打印ID列内容,同时处理行内列数不足的情况 for (const auto& row : data) { if (colNum < static_cast<int>(row.size())) { cout << row[colNum] << "\t"; } else { cout << "空值\t"; } } cout << endl; return 0; }
关键修改说明
- 解决越界问题:读取每行前先通过
data.push_back(vector<string>())创建空行,再用data.back()操作当前行,彻底避免索引访问错误。 - 增加异常防护:添加文件打开检查、空文件判断、列名不存在判断,确保程序在异常场景下能给出明确提示而非崩溃。
- 代码优化:使用范围for循环遍历行,简化代码逻辑;预先分配vector空间提升性能;增加行内列数检查,兼容格式不规范的CSV行。
内容的提问来源于stack exchange,提问作者Rao Hamdullah
相关产品推荐
相关产品推荐

