使用stoi转换CSV日期字符串时程序崩溃的问题求助
解决CSV日期转换stoi崩溃问题
问题根源
你遇到的std::invalid_argument错误,本质是**stoi接收到了非数字的空字符串或无效内容**。罪魁祸首是while(!file.eof())的循环逻辑:当文件读到末尾时,getline会读取失败,但循环仍会执行一次,此时date1是空字符串,分割后的month/day/year都是无效值,触发转换报错。
修复方案
核心改进点
- 替换循环条件:用
getline读取整行的方式控制循环,避免eof判断的陷阱 - 增加有效性检查:包括文件打开状态、日期格式完整性
- 添加异常捕获:处理转换失败的情况,避免程序直接崩溃
修复后的完整代码
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> using namespace std; void examineString(const string& s) { cout << "[" << s << "]"; // 保留你的调试函数 } void fileOpener(){ ifstream file("WHO-COVID-data.csv"); // 先检查文件是否成功打开 if (!file.is_open()) { cerr << "无法打开目标文件" << endl; return; } string line; // 读取整行直到文件结束,确保每次循环处理的都是有效行 while (getline(file, line)) { stringstream line_ss(line); string date1, country1, cases1, death1; // 分割当前行的各字段 getline(line_ss, date1, ','); getline(line_ss, country1, ','); getline(line_ss, cases1, ','); getline(line_ss, death1); // 最后一行直接读到换行符 stringstream date_ss(date1); string month, day, year; // 检查日期分割是否成功(确保格式是月/日/年) if (getline(date_ss, month, '/') && getline(date_ss, day, '/') && getline(date_ss, year)) { examineString(month); cout << ","; examineString(day); cout << ","; examineString(year); cout << endl; try { int month_int = stoi(month); int day_int = stoi(day); int year_int = stoi(year); cout << month_int << "," << day_int << "," << year_int << endl; } catch (const std::invalid_argument& e) { cerr << "转换失败:" << e.what() << " | 原始日期:" << date1 << endl; } catch (const std::out_of_range& e) { cerr << "数值超出范围:" << e.what() << " | 原始日期:" << date1 << endl; } } else { cerr << "日期格式错误:" << date1 << endl; } } file.close(); } int main() { fileOpener(); return 0; }
额外说明
- 原代码中
while(!file.eof())的写法是C++文件读取的常见误区,因为eof()只有在读取操作尝试越过文件末尾时才会置位,导致最后一次循环处理无效数据。 - 异常捕获可以让程序在遇到错误数据时继续运行,同时输出清晰的错误信息,便于定位问题。
内容的提问来源于stack exchange,提问作者TheAwesomeNoob5
相关产品推荐
相关产品推荐

