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

时间:2017-11-30 03:51:01

标签: c++ loops user-input dynamic-arrays sentinel

我需要在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 个答案:

答案 0 :(得分:-1)

一些错误:

  1. length永远不会分配值
  2. 您使用newName
  3. 中数组的未分配值x[i]覆盖newName = x[i];
  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
    4. 快乐学习!