-1
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

ADC
  • 3
  • 4
  • One possible reason is that [using namespace std is bad practice](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-in-c-considered-bad-practice). Who knows which getline() you're really calling... – Sam Varshavchik Apr 30 '16 at 02:13
  • This code doesn't count the number of lines in which `"input1"` appears. It counts the number of lines which do not start with `"input1"`. – Benjamin Lindley Apr 30 '16 at 02:17
  • 2
    Why the semicolon after `while (getline(out, temp))` exists? – MikeCAT Apr 30 '16 at 02:21
  • This isn't the problem, but it's odd to have an input file named `out`. – Pete Becker Apr 30 '16 at 11:33

1 Answers1

1

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.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70