for (School school : schools) { if (school.year == year) { cout << "编号:" << school.id << endl; cout << "名称:" << school.name << endl; cout << "地址:" << school.address << endl; cout << "省份:" << school.province << endl; cout << "建校年份:" << school.year << endl; } }修改这段代码能在编译器使用的是 C++98 标准
时间: 2023-08-20 13:13:42 浏览: 73
可以将 range-based for 循环改写成传统的 for 循环,如下所示:
```c++
for (vector<School>::iterator it = schools.begin(); it != schools.end(); ++it) {
School school = *it;
if (school.year == year) {
cout << "编号:" << school.id << endl;
cout << "名称:" << school.name << endl;
cout << "地址:" << school.address << endl;
cout << "省份:" << school.province << endl;
cout << "建校年份:" << school.year << endl;
}
}
```
这样就可以在 C++98 标准下编译通过。注意,在传统的 for 循环中,需要使用迭代器来访问容器中的元素,同时需要使用一个变量来存储每个元素的值。
相关问题
// 从文件中加载参赛队伍信息 void loadTeamsFromFile(vector<Team>& teams) { ifstream inFile("team.txt"); if (!inFile.is_open()) { cout << "无法打开team.txt文件!" << endl; return; } string line; while (getline(inFile, line)) { stringstream ss(line); Team team; if (ss >> team.id) { ss >> std::ws; getline(ss, team.name, '\t'); ss >> std::ws; getline(ss, team.school, '\t'); ss >> std::ws; getline(ss, team.category, '\t'); ss >> std::ws; getline(ss, team.players, '\t'); ss >> std::ws; getline(ss, team.coach); cout << "id: " << team.id << ", name: " << team.name << ", school: " << team.school << ", category: " << team.category << ", players: " << team.players << ", coach: " << team.coach << endl; teams.push_back(team); } else { cout << "无效行:" << line << endl; } } }// 按学校查询参赛队伍信息 void searchBySchool(vector<Team>& teams) { string school; cout << "请输入要查询的学校名称:" << endl; cin >> school; bool found = false; for (auto& team : teams) { if (team.school == school) { cout << "编号:" << team.id << endl; cout << "名称:" << team.name << endl; cout << "学校:" << team.school << endl; cout << "类别:" << team.category << endl; cout << "参赛者:" << team.players << endl; cout << "教练姓名:" << team.coach << endl; found = true; } } if (!found) { cout << "无法找到该学校参赛队伍,请检查输入是否正确!" << endl; } }在运行输入的学校无误后显示未查找到该学校的参赛队伍
可能是因为加载参赛队伍信息时,有些行的学校名称与你输入的学校名称不完全一致,导致无法找到对应的参赛队伍。
你可以尝试修改 `searchBySchool` 函数,使用字符串的 `find` 函数来判断参赛队伍的学校名称中是否包含输入的字符串,从而实现模糊匹配。具体代码如下:
``` c++
// 按学校查询参赛队伍信息
void searchBySchool(const vector<Team>& teams) {
string school;
cout << "请输入要查询的学校名称:" << endl;
cin >> school;
bool found = false;
for (const auto& team : teams) {
if (team.school.find(school) != string::npos) {
cout << "编号:" << team.id << endl;
cout << "名称:" << team.name << endl;
cout << "学校:" << team.school << endl;
cout << "类别:" << team.category << endl;
cout << "参赛者:" << team.players << endl;
cout << "教练姓名:" << team.coach << endl;
found = true;
}
}
if (!found) {
cout << "无法找到包含 " << school << " 的参赛队伍,请检查输入是否正确!" << endl;
}
}
```
这样就可以实现模糊匹配,查找到包含输入的字符串的参赛队伍了。
阅读全文