简体   繁体   中英

Reading lines from file with while(getline()) not working

ifstream out("output.txt");
string search = "input1";
int count = 0;

while (getline(out, temp));
{
    if (temp.find(search))
    {
        count++;
    }
}

cout << "Total times input1 is present in output.txt: " << count << endl;

I am trying to count the number of times "input1" shows up in my output file. cout shows 1, when it should show 4. Putting a cout between the while and if statements shows that my getline() is not reading a line.

While testing, I used getline() before this while loop, and it picked everything up just fine.

Output.txt:

This is the first line in input1.txt.
This is the first line in input2.txt.
This is the second line in input1.txt.
This is the second line in input2.txt.
This is the third line in input1.txt.
This is the third line in input2.txt.
This is the fourth line in input1.txt.
This is the fourth line in input2.txt.

After a while of testing and searching the internet I still have no idea what I am doing wrong. Any help would be appreciated.

Thanks

The semicolon after while (getline(out, temp)) is getting the block containing the if statement out of the loop and having the find function see only the last line in the file. Try removing it.

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