C++读取逗号分隔TXT文件并将各列存入数组/vector求助
解决C++读取CSV文件并拆分到对应容器的问题
首先看你提供的示例数据,应该是两条课程记录(排版时换行未正常显示):
AI323,12,soma gomez,Wed,department of art
AM324,6,tony wang,Tue;Thu, CC+ dance school
下面是完整的代码实现,用getline配合stringstream正确拆分逗号分隔的字段,同时兼容字段内的空格:
#include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> #include <stdexcept> using namespace std; int main() { // 定义对应列的容器 vector<string> course_codes; vector<int> student_counts; vector<string> teacher_names; vector<string> dates; vector<string> locations; // 打开目标文件 ifstream input_file("school_database.txt"); if (!input_file.is_open()) { cerr << "无法打开文件!" << endl; return 1; } string line; // 逐行读取文件内容 while (getline(input_file, line)) { stringstream line_stream(line); string field; vector<string> fields; // 按逗号拆分当前行的所有字段 while (getline(line_stream, field, ',')) { // 清理字段开头的冗余空格(比如地点字段的前置空格) size_t start_pos = field.find_first_not_of(" "); if (start_pos != string::npos) { field = field.substr(start_pos); } fields.push_back(field); } // 检查字段数量是否符合预期(每条记录需5个字段) if (fields.size() != 5) { cerr << "行格式错误:" << line << endl; continue; } // 将字段存入对应容器 course_codes.push_back(fields[0]); try { // 将学生人数字符串转为整数 student_counts.push_back(stoi(fields[1])); } catch (const invalid_argument& e) { cerr << "学生人数格式错误:" << fields[1] << endl; continue; } catch (const out_of_range& e) { cerr << "学生人数数值超出范围:" << fields[1] << endl; continue; } teacher_names.push_back(fields[2]); dates.push_back(fields[3]); locations.push_back(fields[4]); } // 关闭文件 input_file.close(); // 验证读取结果(可选) cout << "读取结果:" << endl; for (size_t i = 0; i < course_codes.size(); ++i) { cout << "课程代码:" << course_codes[i] << " | 学生人数:" << student_counts[i] << " | 教师姓名:" << teacher_names[i] << " | 日期:" << dates[i] << " | 地点:" << locations[i] << endl; } return 0; }
关键细节说明:
- 整行读取:用
getline(input_file, line)读取完整行,避免cin被空格截断的问题,能完整保留带空格的字段(比如教师姓名)。 - 字段拆分:借助
stringstream处理单行内容,再用getline(line_stream, field, ',')按逗号拆分字段,完美适配CSV格式。 - 冗余处理:添加了字段开头空格的清理逻辑,解决类似
CC+ dance school这种前置空格的问题。 - 错误防护:包含文件打开失败、字段数量不符、数值转换失败的错误提示,避免程序意外崩溃。
你之前用getline失败,大概率是没处理字段内的空格或错误使用了cin读取,这个方案可以直接解决你的需求。
内容的提问来源于stack exchange,提问作者mahtab shahrivand
相关产品推荐
相关产品推荐

