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

Gau*_*kur 0 c++

我正在尝试通过指针访问结构。我认为问题出在第 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Bat*_*eba 5

问题确实归结为

friends *dost[numberOfFriends];
Run Code Online (Sandbox Code Playgroud)

您不会为指针分配任何内存,并且变长数组也不是可移植的。

替换是

std::vector<friends> dost(numberOfFriends);
Run Code Online (Sandbox Code Playgroud)

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

  • 是的,我可以,但这将是一个*非常*劣质的解决方案。 (3认同)