简体   繁体   中英

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

There are two problems with your code:

  • see Why is iostream::eof inside a loop condition (ie `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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM