我需要在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;
}
任何帮助将不胜感激。
一些错误:
-
length
从未分配一个值 - 您正在用
newName = x[i];
中的数组的未分配值x[i]
覆盖newName
-
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
快乐学习!