横向C 中的结构误差数组

Transversing an Array of structs error in C++

本文关键字:误差 数组 结构 横向      更新时间:2023-10-16

当前代码:

const int MAX_CODENAME = 25;
const int MAX_SPOTS = 5;
struct Team  {    
string TeamName[MAX_CODENAME];  
short int totalLeagueGames;  
short int leagueWins;  
short int leagueLoses;  
}; 
//GLOBAL VARIABLES:
 Team league[MAX_SPOTS];

void addTeams(){
int i = 0; //first loop
int j; //second loop
while(i < MAX_SPOTS){
    cout << "****** ADD TEAMS ******" << endl;
    cout << "Enter the teams name " << endl;
    scanf("%s", league[i].TeamName) ;
}
void searchTeam(){
   string decider[MAX_CODENAME];
   cout << "Please enter the team name you would like the program to retrieve: " << endl;
   cin >> decider[MAX_CODENAME];
for(int i = 0; i < MAX_SPOTS; i++){
    if(decider == league[i].TeamName){
        cout << endl;
        cout << league[i].TeamName << endl;
        break;
    }else{
        cout << "Searching...." << endl;
    }

}

}

我真的不知道为什么它不起作用,但是我包含了所有可行的标头文件,例如和,但是当我输入数据然后尝试搜索时,程序会崩溃。我得到了死亡圈,然后程序不响应,然后说流程返回255(0xff)。它甚至没有搜索搜索.... 我在输入该名称后实际上就放弃了该程序。

也可以通过使用指示器来优化这将是很棒的。

tl; dr运行时错误,导致搜索输入名称后立即失败。对于记录,我已经检查了以确保我输入的名称有效。

scanfstd::string不了解。使用std::cin >> league[i].TeamName

scanf("%s", league[i].TeamName) ;

应该更改为

std::cin >> league[i].TeamName ;

这里其他几件事....

string decider[MAX_CODENAME];
       cout << "Please enter the team name you would like the program to retrieve: " << endl;
       cin >> decider[MAX_CODENAME];

每次输入一个值时,您都告诉计算机在Decider [25]中保存输入的值,但计算机仅读取索引0-24。

if(decider == league[i].TeamName){

您将团队名称与哪个数组插槽进行比较?如果其第25个要素应为

 if(decider[24] == league[i].TeamName){
如果团队名称的数量未知,则

指示器更适合。根据提出的有限代码,我强烈建议您留在基本数据类型的领域中。出于故障排除的目的,请在将来发布完整的代码。

您的TeamName成员变量:

string TeamName[MAX_CODENAME];  

是25个字符串的数组,因此在此行中:

scanf("%s", league[i].TeamName) ;

您正在勇于阵列。无论如何,您真的不想要一个数组,因此将TeamName声明更改为:

string TeamName;  

然后,当您阅读名称时,您需要使用iostream S知道如何填充string类型(SCANF仅与C char数组一起使用):

std::cin >> league[i].TeamName