I have a program to write that uses an array to read from 2 different files. The first file is named Teams.txt and displays all the MLB teams that have won the World Series since 1903. The second file is WolrdSeriesWinners.txt and it has all the winners in chronological order from 1903-2013. The first part of the code will open the first file and write the names that the user is to choose from and works just fine. The problem I am having is trying to figure out how to make the second part which will tell the user how many times the team they selected has won. Any help would be appreciated.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main ()
{
cout<<"MLB teams that have won the World Series at least once :\n";
cout<<"========================================================\n";
constint SIZE = 28;
string array[SIZE];
int i=0;
string line;
ifstream in ("Teams.txt");
if (in.is_open())
{
while (! in.eof() )
{
getline (in,line);
array[i] = line;
cout << array[i] << endl;
i++;
}
in.close();
}
string tempstr, team;
int count, num;
count = 0;
num = 0;
ifstream infile ("WorldSeriesWinners.txt");
cout<<"Choose a team from the list and see how many times they have won since 1903.\n";
getline(cin,team);
while(infile >> tempstr)
{
if(tempstr == team)
{
num++;
}
count++;
}
cout<< "The " << team << " have won the World Series " << num << " times since 1903.\n";
system("PAUSE");
return 0;
}
It might be your use of the insertion operator. It will take a string of data up until a space. That means if the user wants to see how many times the "New York Yankees" won the World Series, the insertion operator will read in and subsequently compare each individual world from the file. So while the Yankees have won multiple World Series, the insertion operator will read in like so:
"New", "York", "Yankees". These three individual strings will never be equivalent to "New York Yankees" as a result.
tl;dr you should probably use the getline function when you read in the second file.
I understand what you're saying but I have never used a getline to read from a file before. I used the getline to capture all of the user input for the same reason. Would it looks something like