要解决“遍历结构体数组并存储数值的操作无法正常工作”的问题,您可以尝试以下解决方法:
下面是一个示例代码,展示了如何遍历结构体数组并存储数值的正确操作:
#include
struct Person {
std::string name;
int age;
};
void storeValues(Person* people, int size) {
for (int i = 0; i < size; i++) {
std::cout << "Enter name for person " << i + 1 << ": ";
std::cin >> people[i].name;
std::cout << "Enter age for person " << i + 1 << ": ";
std::cin >> people[i].age;
}
}
void printValues(const Person* people, int size) {
for (int i = 0; i < size; i++) {
std::cout << "Person " << i + 1 << ": " << people[i].name << ", " << people[i].age << std::endl;
}
}
int main() {
const int size = 3;
Person people[size];
storeValues(people, size);
printValues(people, size);
return 0;
}
在上述示例中,我们首先定义了一个Person结构体,具有name和age字段。然后,我们定义了一个storeValues函数,用于遍历结构体数组并存储用户输入的数值。接着,我们定义了一个printValues函数,用于打印存储的数值。最后,在main函数中,我们声明了一个包含3个Person结构体的数组,并调用storeValues和printValues函数来演示正确的操作。