如何允许无限数量的名称输入

How to allow unlimited number of names for input?

本文关键字:输入 何允许 无限      更新时间:2023-10-16
    #include <iostream>
    using namespace std;
    #include "ReadString.h"

    void main()
    {
        int     i ;
        int     NumNames=5;
        char ** pNames;
         int MaxNum = 10;
        int more(0);
        pNames = new char *[NumNames];

        cout << "Enter  names" << endl;

这是我遇到麻烦的部分。我以不同的方式尝试,但没有成功。我试图做一个循环,除非第一个字符是"回车键"。

while(cin.get()!='n')
{
        for (i = more; i < NumNames; i++)
        {
                cout << (i + 1) << ") ";
                pNames[i] = ReadString();
                more = NumNames;
                NumNames +=NumNames
        }
}

将手动分配的动态数组替换为一些可以动态增长的容器,例如std::vector

std::vector<std::string> names;
std::string name;
// read the names
while (cin >> name) {
    names.push_back(name);
}