string firstname, lastname;
string phonenumber, email;
cout << "What is the first of the person that you would like to add? : ";
cin >> firstname;
cout << "What is the last of the person that you would like to add? : ";
cin >> lastname;
cout << firstname << " " << lastname << endl;
cout << "What is the phone number of that person? : ";
cin >> phonenumber;
我需要帮助获取此用户输入并将其插入数组。老实说,我不知道该怎么做,如果我能得到一些帮助,那就太好了!
最佳答案
如下创建一个名为Record的结构
struct Record
{
string firstName, lastName,phone; //etc
};
如果您知道要输入多少条记录,那么您必须创建一个记录数组,如下所示
Record PersonInfo[5];
现在 PersonInfo 的每个索引假设 PersonInfo[2] 是一个完整的记录,您可以访问那里的字段,例如
PersonInfo[2].phone = "5655567" //etc
现在,如果您想创建 Record 数组但不知道大小,那么您现在最好的选择是使用如下所示的 vector 。 vector 是可变大小的数组。您需要包含以下 header
#include<vector>
之后你可以做以下事情
vector<Record> PersonInfo //thats how vectors are declared
<> bractes 之间的名称告诉你想要什么类型的 vector ,你也可以写 int 。 以下是如何将项目添加到 vector
Record r1,r2; // just for example
PersonInfo.push_back(r1);
PersonInfo. push_back(r2);
您可以在其中添加任意数量的项目,您可以像访问数组一样访问它们
PersonInfo[0] .lastName // its actually r1.lastName and so on
目前这似乎很难,您可能想在进行动态内存分配之前学习 vector 及其操作,这需要您了解什么是指针。我不知道你是否了解指针以及如何使用它们,这就是为什么我向你推荐 vector
关于c++ - 获取用户输入并将其插入动态分配数组,初级 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41043784/