我需要在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;
}
非常感谢任何帮助。
答案 0 :(得分:-1)
一些错误:
length
永远不会分配值newName
x[i]
覆盖newName = x[i];
x
永远不会使用不同length
让我们考虑一个解决方案:
#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;
}
解决上述错误:
length
在开始时分配了默认值x[i] = newName;
x
动态分配一个指数增加的新数组length
快乐学习!