C++读取TSV文件时无效日期输入引发无限循环的解决求助
解决文件读取指定日期时的无限循环问题
我的代码负责打开文件并读取指定日期的数据,但当用户输入文件中不存在的日期时,代码会陷入无限循环,不清楚该如何规避此问题。
原问题代码
#include <iostream> #include <fstream> using namespace std; int main() { ifstream theFile("Current_Reservoir_Levels.tsv"); if (theFile.fail()) { cerr << "File does not open." << endl; exit(1); } string junk; getline(theFile, junk); string wanteddate; string nodate; nodate = "12/31/2018"; cout << "Enter the date you want "; if(wanteddate != nodate) { cin >> wanteddate; string date; double gallons; do { theFile >> date; } while (date.compare(wanteddate) != 0); theFile >> gallons; cout << "East basin storage: " << gallons << endl; theFile.close(); return 0; } else { return 0; } }
问题根源
- 无限循环核心原因:原代码的
do-while循环只判断日期是否匹配,完全没检查文件是否读到末尾。当目标日期不存在时,theFile >> date会持续读取失败,但循环条件还在执着对比日期,直接导致死循环。 - 无效逻辑冗余:开头的
if(wanteddate != nodate)完全没用,wanteddate初始是空字符串,必然不等于"12/31/2018",这段判断纯粹是多余的。 - 数据读取错位:TSV文件每行是日期加储水量数据,原代码只读取
date,跳过了每行其他内容,后续读取gallons时会拿到错误数据。
修复后的代码
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream theFile("Current_Reservoir_Levels.tsv"); if (!theFile.is_open()) { cerr << "文件无法打开。" << endl; return 1; } string junk; getline(theFile, junk); // 跳过表头行 string wanteddate; cout << "请输入想要查询的日期:"; cin >> wanteddate; string date; double gallons; bool found = false; // 循环读取,直到文件末尾或找到目标日期 while (theFile >> date >> gallons) { if (date == wanteddate) { found = true; break; } } if (found) { cout << "东流域储水量:" << gallons << endl; } else { cerr << "未找到指定日期的数据。" << endl; } theFile.close(); return 0; }
关键修改说明
- 用
theFile.is_open()替代fail(),更准确判断文件是否成功打开。 - 删除了毫无意义的
nodate相关判断,简化代码流程。 - 将
do-while改为while循环,利用theFile >> date >> gallons的返回值判断读取状态——当文件读到末尾或读取失败时,表达式返回false,自动终止循环,彻底避免无限循环。 - 增加
found布尔标记,明确是否找到目标日期,找不到时给用户清晰提示。 - 直接读取每行的日期和储水量,符合TSV文件列格式,避免数据读取错位。
内容的提问来源于stack exchange,提问作者user20094095
相关产品推荐
相关产品推荐

