用于连续字符串输入的C++动态数组

C++ dynamic array for continuous string input

我需要用 C++ 创建一个动态数组,并要求用户输入名称,直到用户键入 exit

它应该不断询问越来越多的名字,将它们记录到动态字符串数组中,然后从列表中随机选择用户想要的名字。

我应该能够找出随机数部分,但连续输入给我带来了问题。我不确定如何让长度变量继续更改值。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int length;

    string* x;
    x = new string[length];
    string newName;

    for (int i = 0; i < length; i++)
    {
        cout << "Enter name: (or type exit to continue) " << flush;
        cin >> newName;
        while (newName != "exit")
        {
            newName = x[i];
        }
    }
    cout << x[1] << x[2];

    int qq;
    cin >> qq;
    return 0;
}

如有任何帮助,我们将不胜感激。

一些错误:

  1. length 从未被赋值
  2. 您正在用 newName = x[i];
  3. 中数组的未分配值 x[i] 覆盖 newName
  4. x 永远不会动态重新分配不同的 length
  5. 的新数组

让我们考虑一个解决方案:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int length = 2; // Assign a default value
    int i = 0;      // Our insertion point in the array

    string* x;
    x = new string[length];
    string newName;

    cout << "Enter name: (or type exit to continue) " << flush;
    cin >> newName; // Dear diary, this is my first input

    while (newName != "exit")
    {
        if (i >= length) // If the array is bursting at the seams
        {
            string* xx = new string[length * 2]; // Twice the size, twice the fun

            for (int ii = 0; ii < length; ii++)
            {
                xx[ii] = x[ii]; // Copy the names from the old array
            }

            delete [] x; // Delete the old array assigned with `new`
            x = xx;      // Point `x` to the new array
            length *= 2; // Update the array length
        }

        x[i] = newName; // Phew, finally we can insert
        i++;            // Increment insertion point

        cout << "Enter name: (or type exit to continue) " << flush;
        cin >> newName; // Ask for new input at the end so it's always checked
    }

    cout << x[1] << x[2]; // Print second and third names since array is 0-indexed

    int qq;
    cin >> qq; // Whatever sorcery this is
    return 0;
}

解决提到的错误:

  1. length开头赋了默认值
  2. 反转方向得到x[i] = newName;
  3. x 被动态分配了一个新的指数增长数组 length

祝您学习愉快!