C++文本文件查重新增功能异常:无法识别已有数据及代码终止
问题分析与修复方案
核心问题点
- 输入与匹配逻辑不匹配:原代码要求输入姓名+姓氏,但文件仅存储名字,且用子串匹配易误判;若用户只输入名字,
cin >> name >> surname会阻塞等待第二个输入,打乱后续逻辑。 - 文件流作用域冲突:局部
ofstream file覆盖外部ifstream file,后续对已关闭的流执行close()触发未定义行为,导致程序提前终止,无法执行cout << "Hi"这类后续代码。 - 字符串拼接错误:
"\n" + name会触发指针运算而非字符串拼接,写入文件的内容会出错。 - 无终止循环:找到匹配项后仍继续读取文件,浪费资源。
修复后的代码
#include <iostream> #include <fstream> #include <string> #include <sstream> using namespace std; int main(void) { bool foundname = false; ifstream infile("names-genders.txt"); string name, gender, line; cout << "Enter name: "; cin >> name; if (infile.is_open()) { string line_name, line_gender; while (getline(infile, line)) { istringstream iss(line); if (iss >> line_name >> line_gender) { if (line_name == name) { gender = line_gender; foundname = true; break; } } } infile.close(); } else { cout << "Warning: Database file not found, will create new one." << endl; } if (!foundname) { ofstream outfile("names-genders.txt", ios::app); if (outfile.is_open()) { cout << "Name not found in database. Please enter the gender: "; cin >> gender; outfile << '\n' << name << " " << gender; outfile.close(); } else { cout << "Error: Cannot open file for writing." << endl; } } cout << "Hi" << endl; return 0; }
关键修复说明
- 精确匹配名字:用
istringstream拆分每行内容,直接对比完整名字,避免子串匹配的误判(比如不会把"Fedorov"当成"Fedor")。 - 分离读写流变量:用
infile和outfile分别处理读、写操作,彻底避免作用域覆盖导致的流操作异常。 - 修复字符串写入:用
<<运算符依次输出内容,避开C风格字符串与std::string拼接的错误逻辑。 - 增加文件状态检查:处理文件不存在的情况,提升程序鲁棒性。
- 及时终止循环:找到匹配项后立即
break,减少不必要的文件读取操作。
内容的提问来源于stack exchange,提问作者Фёдор Руденко
相关产品推荐
相关产品推荐

