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

C++ 需要弄清楚为什么代码没有从文件中读取数据并给出错误的答案,c++,C++,我需要帮助理解我在编码(c++)中的错误。然后,每当我在输出中输入球队名称时,程序应显示该队赢得世界大赛的次数。相反,我得到的是:纽约洋基队赢得了世界系列赛0次。 这是我的密码: #include <iostream> #include <array> #include <stream> using namespace std; int main() { //variables string teams, winners; string TeamsList[

我需要帮助理解我在编码(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;
 }
#包括
#包括
#包括
使用名称空间std;
int main()
{
//变数
弦乐队,优胜者;
字符串TeamsList[200]={};
字符串WinnerList[200]={};
int计数器=0;
//开放文件团队
ifstream团队文件;
teamsFile.open(“Teams.txt”);
//如果未打开,则显示“错误”
如果(!teamsFile){

当你在这里获得团队名称时,我怀疑你的输入有问题

cout << "\n Enter Team Name to verify it's World Series Wins: \n";
getline(cin, name);
e、 g.输入
newyorkyankes
(末尾有空格)与字符串
winner
不匹配(或者问题可能是
Winners.txt
在球队名称周围有空格或其他内容)。使用调试器帮助确定出现问题的原因,您可以使用以下诊断方法:

std::cout<<"Got winner ["<<winner<<"]\n";
if(winner == name) {
    counter++;
    std::cout<<'['<<winner<<"] matches with ["<<name<<"]\n";
}
这应该是相反的

Winners[Winner++] = winner;

存储从文件读取的实际
获胜者
而不是从用户输入读取的
名称

现在最好在调试器中运行此操作,并逐步检查代码以确保它符合您的预期。您的帮助非常有用。但是,现在每当我在团队中输入名称时,答案是他们赢得了116次。我加入的所有团队都会发生这种情况。我是编程新手,我很困惑。请你帮我或向我解释一下我在做什么wrong@Karla你们能分享一下你们的新代码是什么样子的吗?另外,一定要通过这个链接并使用这个网站来调试你们的程序。慢慢来,但学习调试对于修复这个问题来说是非常必要的正在编辑程序。我刚刚编辑了代码,您可以看到代码与上一个代码略有不同。@Karla您有一行
if(winners==winners)
在您的代码中。这将始终是正确的,并且最后的
计数器的值基本上是
WorldSeriesWinners.txt
中的条目总数。我认为您需要将其更改为
如果(团队==winners)
。另外,您从未在
团队列表
数组中存储任何内容。我不确定它的用途。
while(getline(inputFile, winner)){
    Winners[Winner++] = name;
Winners[Winner++] = winner;