我想设置一个字符串数组,其大小和内容取决于用户输入。我得到一个错误声明我的数组,它说大小的变量不是正确的类型。我花了几个小时就想我会问。C++根据用户输入声明一个包含内容和大小的字符串数组
这里是我的代码:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter number of names /n";
int a;
cin >> a;
string namesArray[a]; //Error is here.
for(int i=0; i<a; i++) {
string temp;
cin >> temp;
namesArray[i] = temp;
}
for(int j=0; j<a; j++) {
cout << "hello " << namesArray[j] << "/n";
}
return 0;
}
的错误是在string namesArray[a];
变量不能用作数组大小,您必须使用编译时常量。你想要的是'std :: vector',一个运行时可调整大小的数组类。 –
请发布您正在收到的确切错误。 –