横向C 中的结构误差数组
Transversing an Array of structs error in C++
当前代码:
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运行时错误,导致搜索输入名称后立即失败。对于记录,我已经检查了以确保我输入的名称有效。
scanf
对std::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
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '