Counting from a file help!

I'm trying to count the number of items from a little list I compiled in NotePad. Here's what the list looks like.
"apple
banana
orange
strawberry
kiwi
berries
plum
orange
orange
kiwi"

So in my program I am trying to count the number of instances of "orange" and "kiwi". So the correct answer should be 3 oranges and 2 kiwis. However my program is telling me 2 oranges and 1 kiwi. Why is that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	
	ofstream outFile;
	ifstream inFile;
	string itemO, itemK;
	int countOrange = 0;
	int countKiwi = 0;


	inFile.open("list.txt");

	//Check for error

	if (inFile.fail())
	{
		cerr << "Error Opening File." << endl;
		exit(1);
	}

	//Read a file until you've reached the end
	while(!inFile.eof())
	{
		inFile >> itemO;
		if (itemO == "orange")
		{
			countOrange++;
		}

		inFile >> itemK;
		if (itemK == "kiwi")
		{
			countKiwi++;
		}
	}

	inFile.close();

	cout << countOrange << " instances of Orange found!\n" << endl;
	cout << countKiwi << " instances of Kiwi found!\n" << endl;

return 0;
}
Last edited on
Never mind guys! A little bit of playing around led me to this. It works great! :)
I'm gonna leave this up for reference in case any one else runs into a similar problem.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
	
	ofstream outFile;
	ifstream inFile;
	string item;
	int countOrange = 0;
	int countKiwi= 0;


	inFile.open("list.txt");

	//Check for error

	if (inFile.fail())
	{
		cerr << "Error Opening File." << endl;
		exit(1);
	}

	//Read a file until you've reached the end
	while(!inFile.eof())
	{
		inFile >> item;
		
		if (item == "orange")
		{
			countOrange++;
		}
		else if (item == "kiwi")
		{
			countKiwi++;
		}
	}

	inFile.close();

        cout << countOrange << " instances of Orange found!\n" << endl;
	cout << countKiwi << " instances of Kiwi found!\n" << endl;

return 0;
}
Last edited on
Topic archived. No new replies allowed.