Home > Back-end >  C Program is not finding the searched word - except the first line
C Program is not finding the searched word - except the first line

Time:09-22

Task: Create program to read given text file and print into another text file all lines containing given substring. Reading from files should be carried out line per line.

My code:

#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!";
}

Problem: I can find the word that I'm searching for in the first line. But not in the following lines (after Enter, \n)!

CodePudding user response:

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

CodePudding user response:

I know this question has been answered but in the event that you need to process multiple key words on a single line you can use the example code I have below.

const std::string needle{ "KeyWord" };

if ( std::fstream file{ R"(Path\To\Your\File\Test.txt)", std::ios::in } ) 
{
    for ( std::string line; std::getline( file, line ); ) 
    {
        std::size_t pos{ line.find( needle ) };
        for ( ; pos != std::string::npos; pos = line.find( needle, pos   needle.size( ) ) ) 
        {
            std::cout << line.substr( pos, needle.size( ) ) << '\n';
        }
    }
}
  • Related