[英]Dynamic Array Size and crashing at getline();
我最近一直在研究一个程序,该程序将名称作为输入,并将最终对它们进行排序和二进制搜索。 但是,在尝试使数组具有动态大小(每次循环迭代将增加一个)时,就会遇到各种问题。
我可以使字符串数组由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);
数组一旦创建便无法调整大小。 您必须销毁它,并使用现有数据的副本创建一个新阵列。 例如:
#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
:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void main()
{
vector<string> Names;
string Name;
Names.reserve(20); // optional
cout << " Enter your names to be sorted\n";
cout << "To exit just press [Enter] at any time\n";
do
{
cout << Names.size() << endl;
cout << "\n< Name " << (Names.size() + 1) << " > = ";
if ((!getline(cin, Name)) || Name.empty())
break;
Names.push_back(Name);
}
while (true);
cout << "\nFinal Name Amount = " << Names.size() << endl << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.