storing to array from a txt file, comparing it with user input.

Hello, I have two txt files where I am displaying baseball teams, and then asking the user to pick a team, and then the program is supposed to tell the user how many times that team has won the world series. (second txt file has a list of the teams that have won over the past 109 years.) Can someone help me out with getting the users input, and then comparing it to the second file. My logic is that if I store the second file with the list of world series winners in an array teamName[j]; then when I get the users input and == to the array, if it is true, it should tally up (num++).

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()
{
	const int SIZE = 28;
	string teams;
	string teamsName[SIZE];
	ifstream inputFile;
	int i = 0;
	inputFile.open("Teams.txt");
	
	while (!inputFile.eof())
	{
		getline(inputFile,teams);
		teamsName[i] = teams;
		cout << teamsName[i] << endl;
		
	} 
	inputFile.close();
	
	//ifstream inputFile;
	string team;
	string getTeam;
	string teamName[108];
	int j = 0;
	int num = 0;

	inputFile.open("WorldSeriesWinners.txt");
	while (!inputFile.eof())
	{
		getline(inputFile,team);
			teamName[j] = team;
			cout << teamName[j] << endl; //To test if teamName[j] would read the teams successfully.
	}
	
	cout << "Choose a team." << endl;
	cin >> getTeam;
	if (getTeam == teamName[j])
	{
		num++;
	}
	cout << num << endl;

	return 0;
}
Hello vessel91,

A few thing I noticed: after line 13 you should check to make sure the file is open or exit the program if not. Not a good idea to check for eof() this does not work the way you expect. The getline will try to read past end of file before the eof bit is set and checked. The while loop may work better as while (getline(inputFile, team[s]. Then in your loops you refer to teamsName[i] and teamName[j], but i and j never change in value, so you are storing everything in the files at team(s)Name[0]. Not What you want.

Line 41 the if statement should be inside a for loop to transverse the entire teamName array.

Without any example of what the input files look like it is hard to test the program any farther beyond does it compile. Not saying I need the entire file say 5 to 10 entries just to get an idea.

Hope that helps,

Andy

Topic archived. No new replies allowed.