首页 > 解决方案 > 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)!

标签: c++filetexttext-processing

解决方案


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;
}
        

推荐阅读