1

我编写了一个哨兵控制的 C++ 程序,您必须在其中输入一组名称。您可以输入的名称数量没有限制。输入完名称后,只需键入“1”即可退出。这是我的代码:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    int nofPeople = 0;
    cout<<"Enter a name or 1 to quit:\n";
    cin>>name;
    while(name != "1")
    {
        nofPeople = nofPeople + 1;

        cout<<"Enter another name or 1 to quit:\n";
        cin>>name;
    }
}

现在我想创建一个长度等于“nofPeople”的数组,并且我希望该数组的元素是我已经输入的名称。我怎么做?

4

2 回答 2

1

您可以使用std::vectorand 它的push_back方法将名称添加到用户输入的向量中。

于 2015-02-10T10:05:50.407 回答
0

执行此操作的标准方法是创建一个std::vector<std::string>,您将在收到字符串时将其添加到其中,最后(一旦您收集了所有字符串)将向量转换为数组。

但是,除非还有其他一些您没有提到的奇怪要求,否则我强烈建议您忘记使用数组并在整个程序中继续使用向量。

于 2015-02-10T10:04:15.387 回答