c++ - C++ 程序没有找到搜索的单词 - 除了第一行
问题描述
任务:创建程序以读取给定的文本文件并将包含给定子字符串的所有行打印到另一个文本文件中。从文件中读取应该逐行进行。
我的代码:
#include <iostream>
#include <fstream>
#include <sstream>
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());
string keyWord;
cout << "Please, enter a key word: " << endl;
cin >> keyWord;
string line;
while (getline(inputfile, line)) {
// Processing from the beginning of each line.
if(line.find(keyWord) != string::npos){
outputFile << "THE LINE THAT IS CONTAINING YOUR KEY WORD: " << "\n"
<< line << "\n";
} else
cout << "Error. Input text doesn't have the mentioned word." << endl;
break;
}
cout << "An output file has been created!";
}
问题:我可以在第一行找到我要搜索的单词。但不在以下几行中(在 Enter 之后,\n)!
解决方案
int found = 0;
while (getline(inputfile, line)) {
// Processing from the beginning of each line.
if(line.find(keyWord) != string::npos){
outputFile << "THE LINE THAT IS CONTAINING YOUR KEY WORD: " << "\n"
<< line << "\n";
found = 1;
}
}
if(found == 0)
{
cout << "Error. Input text doesn't have the mentioned word." << endl;
}
推荐阅读
- axios - 扩展 Nuxt Auth 插件时 Axios 拦截器不起作用
- c# - 在用作委托的静态方法中访问 DbContext
- cakephp - CakePHP 3 - 如何在 View Cell 中设置 CSS / Script 块
- reactjs - 为什么 react-navigation 的 setParams() 在一个组件中工作而不是在另一个组件中工作?
- google-sheets - 如何在查询或数组公式的末尾显示一些文本?
- c# - 我可以做些什么来限制用户输入字母(a,b,c,d..)和其他字符(<,>,@<,!...)
- mysql - 按最新值sql分组
- .net - Azure 媒体服务:获取需要编码的视频的时长
- winapi - SetWindowLong 与 SetWindowLongPtr
- google-sheets - 通过过滤掉零值来创建帮助表