程序不接受任何输入.第一次输入后,它会自动关闭

The program is not taking any input. After very first input it closes automatically

本文关键字:输入 不接受 任何 第一次 程序      更新时间:2023-10-16

我正在尝试通过指针访问结构。我认为问题出在第 13 行。谁能告诉我问题到底是什么以及如何解决?

    #include <iostream>
struct friends {
    std::string name;
    std::string lastName;
    int age{};
};
int main() {
    using namespace std;
    int numberOfFriends{0};
    cout << "Please enter the number of the friends: ";
    cin >> numberOfFriends;
    friends *dost[numberOfFriends];
    for (int i = 0; i < numberOfFriends; ++i) {
        cout << "Please enter the name of " << i + 1 << " friend: ";
        cin>>(dost[i]->name);
        cout << "Please enter the last name of " << i + 1 << " friend: ";
        cin >> dost[i]->lastName;
        cout << "Please enter the age of " << i + 1 << " friend: ";
        cin >> dost[i]->age;
    }
    cout << "You entered following data. Please have a look: " << endl;
    cout << "****************************************************" << endl;
    for (int j = 0; j < numberOfFriends; ++j) {
        cout << "Friend     :" << j + 1 << endl;
        cout << "Name       :" << dost[j]->name << endl;
        cout << "Last Name  :" << dost[j]->name << endl;
        cout << "Full Name  :" << dost[j]->name << " " << dost[j]->lastName << endl;
        cout << "Age        :" << dost[j]->age << endl;
        cout << "****************************************************" << endl;
    }
}

问题确实归结为

friends *dost[numberOfFriends];

您没有为指针分配任何内存,可变长度数组也不是可移植的。

替换是

std::vector<friends> dost(numberOfFriends);

尽管您需要将dost[i]->替换为dost[i].尽管我倾向于使用dost.at(i).,因为这会对索引进行运行时边界检查。