C++逐行读文件匹配关键字程序仅首行匹配成功问题排查
问题原因
break语句位置错误:你写的break不属于if或else的分支内,不管第一行有没有匹配到关键词,第一次循环结束后都会直接跳出循环,导致后续行根本不会被读取。- 输入缓冲区残留换行符:用
cin >> keyWord读取关键词后,输入缓冲区会留下一个换行符,第一次执行getline时会直接读取到空串,跳过文件第一行的实际内容。 - 错误提示逻辑不合理:当前逻辑是只要某一行没匹配到关键词就输出错误提示,不符合“全文件找不到才报错”的需求。
修复方案
- 删除多余的
break语句,让while循环可以遍历文件所有行 - 读取关键词后添加
cin.ignore()清除缓冲区残留的换行符 - 新增匹配标记变量,遍历完所有行后再判断是否输出未找到的提示
- 补充文件打开成功的校验,避免文件不存在时程序无响应
修正后代码
#include <iostream> #include <fstream> #include <string> using namespace std; int main(){ string inputFileName = "inputFile.txt"; string outputFileName = "outputFile.txt"; fstream inputfile; ofstream outputFile; inputfile.open(inputFileName.c_str()); outputFile.open(outputFileName.c_str()); // 补充文件打开校验 if(!inputfile.is_open() || !outputFile.is_open()){ cout << "文件打开失败,请检查路径是否正确" << endl; return 1; } string keyWord; cout << "Please, enter a key word: " << endl; cin >> keyWord; // 清除缓冲区残留换行符 cin.ignore(); string line; bool hasMatch = false; while (getline(inputfile, line)) { if(line.find(keyWord) != string::npos){ hasMatch = true; outputFile << "THE LINE THAT IS CONTAINING YOUR KEY WORD: " << "\n" << line << "\n"; } } if(!hasMatch){ cout << "Error. Input text doesn't have the mentioned word." << endl; } cout << "An output file has been created!"; // 关闭文件释放资源 inputfile.close(); outputFile.close(); return 0; }
内容的提问来源于stack exchange,提问作者Robert Kovalauskis
相关产品推荐
相关产品推荐

