Hudie
Hudie

Reputation: 49

How to use getline to print the correct line from txt file

I'm trying to create a program that will search a given directory txt file for a certain string. Once that string is found, the program will print onto the screen the information only on that line within the txt file. My code is able to check and see if the string is inside the file, but instead of printing only the line it's contained in, it prints everything but the line I want.

while(!inF.eof()){
    getline(inF, hold);
    if(hold.find(crnS)){
        isFound = 1;
        cout << hold << endl; 
    }                          
}

Upvotes: 1

Views: 48

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596703

There are two problems with your code:

  • see Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?

  • std::string::find() returns an index, not a bool. Any non-zero value is evaluated as true, so any return value other than index 0 will satisfy your if statement, including std::string::npos (-1) if find() does not find a match. That means your code outputs each line where crnS is found anywhere other than at very beginning of the line, as well as when crnS is not found at all.

Use this instead:

while (getline(inF, hold)) {
    if (hold.find(crnS) != string::npos) {
        isFound = 1;
        cout << hold << endl;
    }
}

Upvotes: 1

Related Questions