首页 > 解决方案 > 在 C++ 中显示一个初始化的结构数组

问题描述

我有大量这样的代码:

struct SoccerTeam
{
    string teamName;
    int totalGame;
    SoccerPlayer playerStore[PLAYERS] = { { "NONE", 0 }, { "NONE", 0 }, { "NONE", 0 }, { "NONE", 0 }, { "NONE", 0 } };
};

//Function prototypes.
void showStats(SoccerTeam team[], bool);
void getTeamInfo(SoccerTeam team[]);

//Main function.
int main()
{
    bool flag = true;
    SoccerTeam leagueTeam[TEAM] = { { "NONE", 0, "NONE"}, { "NONE", 0, "NONE"}, { "NONE", 0, "NONE"}, { "NONE", 0, "NONE"} };

    //Call the function to print out the content of the initialized array.
    showStats(leagueTeam, flag);

    //Call the function to ask the user to enter values into the array.
    getTeamInfo(leagueTeam);

    //Call the show stat function again with user's input.
    showStats(leagueTeam, flag);
}

我正在尝试使用以下函数将初始化的数组显示到屏幕上:

//Function that displays the contents of the array to the screen.
void showStats(SoccerTeam team[], bool flag)
{
    double averageG = 0.00;

    cout << "Data After Initialization:" << endl << endl;
    
    for (int i = 0; i < TEAM; i++)
    {
        cout << "The team: " << team[i].teamName << " has played " << team[i].totalGame << " games." << endl;

        for (int j = 0; j < PLAYERS; j++)
        {
            cout << right << setw(20) << "Player: " << team[j].playerStore->playerName << " has " << team[j].playerStore->goalScore << " goals. " << endl;
            averageG = team[j].playerStore->goalScore / team[j].totalGame;
            cout << "The average goals are: " << averageG << endl;
        }
    }
}

并且输出只显示第一行和第三行。我不知道它有什么问题。我是结构新手,但我很难理解这一点:

在此处输入图像描述

标签: c++arraysloopsstruct

解决方案


您的错误代码清楚地表明:

0xc0000094 整数除以零异常

来自这条线:

averageG = team[j].playerStore->goalScore / team[j].totalGame;

此外,这看起来不正确:

SoccerTeam leagueTeam[TEAM] = { { "NONE", 0, "NONE"}, { "NONE", 0, "NONE"}, { "NONE", 0, "NONE"}, { "NONE", 0, "NONE"} };

推荐阅读