<分区>
我正在尝试初始化字符串数组,但出现错误。注意:这适用于 int 数组
。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
cin >> n;
string names[n]; //error here
}
<分区>
我正在尝试初始化字符串数组,但出现错误。注意:这适用于 int 数组
。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
cin >> n;
string names[n]; //error here
}
最佳答案
包括 <vector>
标题和使用
vector<string> names( n );
如果您想保留现有的设计。
但是,对于 vector
你可以使用 push_back
追加新项目的方法(在末尾添加)。然后要求用户指定大小是没有意义的。相反,让附加最后一项后的 vector 大小成为您的 n
.
关于C++ 初始化字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29573200/