动态数组大小并在getline();

时间:2016-04-26 17:55:07

标签: c++ arrays dynamic size

我最近一直致力于一个以名字作为输入的程序,最终会对其进行排序。二进制搜索它们。但是,在尝试使数组成为动态大小(每次循环迭代时会增加一个)时,它会遇到各种问题。

我可以使字符串数组由20个元素组成,并且程序可以正常工作,但我的任务的额外功劳是使其成为动态大小。目前程序在达到" getline(cin,Names [x]);"时没有任何错误代码崩溃。 我一直在四处搜寻,我知道在这种情况下我更容易做一个向量而不是一个数组,但是我不相信我允许使用向量关于这项任务。

由于

原始代码

using namespace std;
#include <iostream>
#include <string>

void main()
{
    int x = 0;
    string * Names = new string[x];
    bool NameInputEnd(0);

    cout << "    Enter your names to be sorted\n";
    cout << "To exit just press [Enter] at any time\n";

    do
    {
        cout << x << endl;
        cout << "\n< Name " << (x + 1) << " > = ";

        !!**CRASHES HERE**!!

        getline(cin, Names[x]);

        if (Names[x].empty() || x == 19)
        {
            cout << "\nFinal Name Amount = " << (x + 1) << endl << endl;
            NameInputEnd = 1;
            continue;
        }

        x++;

    } while (NameInputEnd == 0);

    delete [] Names;
}

更改

int tempsize(1), x(0);
string * Names = new string[tempsize];
...

do
{
...
    x++;
    tempsize++;
}while (NameInputEnd == 0);

1 个答案:

答案 0 :(得分:1)

创建数组后,无法调整其大小。您必须销毁它并使用现有数据的副本创建一个新数组。例如:

Accept

你真的应该使用#include <iostream> #include <string> #include <algorithm> using namespace std; void main() { int x = 0; int capacity = 20; string * Names = new string[capacity]; string Name; cout << " Enter your names to be sorted\n"; cout << "To exit just press [Enter] at any time\n"; do { cout << x << endl; cout << "\n< Name " << (x + 1) << " > = "; if ((!getline(cin, Name)) || Name.empty()) break; if (x == capacity) { int newCapacity = capacity + 20; string *newNames = new string[newCapacity]; copy(Names, Names + x, newNames); delete [] Names; Names = newNames; capacity = newCapacity; } Names[x] = Name; ++x; } while (true); cout << "\nFinal Name Amount = " << x << endl << endl; delete [] Names; } ,但是:

std::vector