```c++ #include <iostream> #include <string> #include <vector> using namespace std; struct Person { int id; string name; int age; char gender; }; vector<Person> persons = { {1, "Tom", 20, 'M'}, {2, "Lucy", 25, 'F'}, {3, "Bob", 30, 'M'}, }; printPerson(Person p) { cout << p.id << "\t" << p.name << "\t" << p.age << "\t" << p.gender << endl; } void queryByName(string name) { bool found = false; for (auto& p : persons) { if (p.name == name) { printPerson(p); found = true; } } if (!found) { cout << "No person with that name." << endl; } } int main() { cout << "ID\tName\tAge\tGender" << endl; for (auto& p : persons) { printPerson(p); } string name; cout << "Enter a name to query: "; cin >> name; queryByName(name); return 0; }这段代码有问题么
时间: 2024-03-13 07:43:18 浏览: 54
是的,这段代码有两个问题。
第一个问题是,在printPerson函数的定义中缺少返回类型。应该在函数定义前加上返回类型,例如void。
第二个问题是,在printPerson函数的调用中缺少参数。应该在函数名后加上括号并传入一个Person类型的参数,例如printPerson(p)。
以下是修正后的代码:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Person {
int id;
string name;
int age;
char gender;
};
vector<Person> persons = {
{1, "Tom", 20, 'M'},
{2, "Lucy", 25, 'F'},
{3, "Bob", 30, 'M'},
};
void printPerson(Person p) {
cout << p.id << "\t" << p.name << "\t" << p.age << "\t" << p.gender << endl;
}
void queryByName(string name) {
bool found = false;
for (auto& p : persons) {
if (p.name == name) {
printPerson(p);
found = true;
}
}
if (!found) {
cout << "No person with that name." << endl;
}
}
int main() {
cout << "ID\tName\tAge\tGender" << endl;
for (auto& p : persons) {
printPerson(p);
}
string name;
cout << "Enter a name to query: ";
cin >> name;
queryByName(name);
return 0;
}
```
阅读全文