需要弄清楚为什么代码没有从文件中读取数据并给我错误的答案



我需要帮助来理解我在编码(c ++)中做错了什么。然后,每当我在输出上输入团队名称时,程序应该显示该团队赢得世界大赛的次数。相反,我一直得到:纽约洋基队赢得了世界大赛 0 次.
这是我的代码:

#include <iostream>
#include <array>
#include <stream>
using namespace std;
int main()
{
//variables
string teams, winners;
string TeamsList[200] = {};
string WinnersList[200] = {};
int counter = 0;
//open file Teams
ifstream teamsFile;
teamsFile.open("Teams.txt");
//If it does not open display "error"
if(!teamsFile){
cout << "error" << endl;
return 0;
}
// If it does open display the content of the file
cout << "Team won World Series: n";
while (getline(teamsFile, teams)){
cout << teams << endl;
}
//close file
teamsFile.close();
//ask for a input
cout << "Enter team name to see if win World Series: n";
getline(cin, teams);
bool found = false;
// Search for the input
for (int i = 0; i < winners.size(); i++){
if(TeamsList[i] == teams){
found = true;
break;
}
}
//open the winners file
ifstream winnersFile;

winnersFile.open(WorldSeriesWinners.txt");
// If it does not open display "error"
if(!winnersFile){
cout << "error" << endl;
return 0;
}
// If it does open count the number of times that the team won
while(getline(winnersFile, winners)){
if(winners == winners)
counter++;
}
//display result
cout << teams << " has won the world series " << counter << " times. 
n ";
winnersFile.close();
return 0;
}

我怀疑当您在此处获取团队名称时,您的输入有问题

cout << "n Enter Team Name to verify it's World Series Wins: n";
getline(cin, name);

如果此name包含空格字符,则与通过此处的winner字符串获取的团队名称不匹配

while(getline(inputFile, winner)){

例如,输入New York Yankees(末尾有一个空格)与字符串winner不匹配(或者问题可能是相反,Winners.txt在团队名称周围有一个空格或其他东西)。使用调试器并帮助确定出现问题的原因,可以使用一些诊断方法,例如:

std::cout<<"Got winner ["<<winner<<"]n";
if(winner == name) {
counter++;
std::cout<<'['<<winner<<"] matches with ["<<name<<"]n";
}

帮助确定输入name是否实际上与读入winner匹配并且没有任何额外的字符。

另一件事是,对于特定问题(和解决方法),您实际上不需要在Teams.txt中读取,因为您只需比较Winners.txt中的读入winner并将其与输入name进行比较,除非当然,在开始将其与Winner.txt中的名称进行比较之前,需要验证输入name是否实际上是有效的团队名称 此外,您的程序中还有一个错误(当前使用时不会出现):

while(getline(inputFile, winner)){
Winners[Winner++] = name;

这应该是

Winners[Winner++] = winner;

存储从文件中读入的实际winner而不是从用户输入读入name

最新更新