c++声明一个基于用户输入的内容和大小的字符串数组
C++ declare a string array with content and size based on user input
我试图建立一个字符串数组,其大小和内容取决于用户的输入。我得到一个错误声明我的数组,它说变量的大小不是正确的类型。我花了几个小时在这个问题上,只是想问一下。
下面是我的代码:
#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];
数组的大小需要有一个编译时的值。你的代码无法编译,因为a
不是编译时常数。
最好使用std::vector
:
#include <iostream>
#include <string>
#include <vector> // <-- Must be included
using namespace std;
int main()
{
cout << "Enter number of names /n";
int a;
cin >> a;
vector<string> namesArray; // HERE!!!
for( int i=0; i < a; i++) {
string temp;
cin >> temp;
namesArray.push_back(temp); // Notice the difference
}
for( int j=0; j<a; j++) {
cout << "hello " << namesArray[j] << "/n";
}
return 0;
}
你可以这样声明你的namesArray:
string * namesArray = new string[a];
这应该可以工作,因为它根据输入值a动态分配内存。
当然,使用vector更好。如果使用vector.
正如Mark所说,这是一个编译时问题。您可以使用vector
,但是另一种方法是动态地为数组分配内存。这意味着使用关键字new
。
string* namesArray = new string[a];
使用new
返回指向数组的指针,因此请相应地调整
您不能使用变量作为静态初始化数组的大小,要做到这一点,您需要动态分配您的数组,如
string* namesArray = new string[a];
但是使用std::vector更明智,可以避免内存泄漏!
对于一个矢量,你可以这样做:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
cout << "Enter number of names /n";
int a;
cin >> a;
vector<string> names;
for( int i=0; i<a; i++) {
string temp;
cin >> temp;
names.push_back(temp);
}
vector<string>::iterator
it = names.begin(),
ite = names.end();
for(; it != ite; ++it) {
cout << "hello " << *it << "/n";
}
return 0;
}
相关文章:
- 检查TCHAR数组输入是否为带符号整数C++
- C++数组输入不接受一定数量的整数
- 为什么我的代码无法处理大型数组输入(>10000)?
- 我正在努力处理多维数组输入和输出,我管理输入,但是打印无法按计划工作
- 使用无符号字符数组输入十六进制数
- C++用用户输入在循环中填充 char 数组:输入整个字符串时到底发生了什么?
- 如何从用户获取数组输入
- C 2x2数组输入线
- 字符数组输入限制
- 将字符串数组输入到函数C++
- C++:如何将普通话(字符串)分配给用户使用数组输入的数字 &运算符问题
- 数组排序、数组输入、数组输出
- 将字符数组输入stdin
- 如何在 c++ 中为对象数组输入字符串
- 如何在c++ mex文件中访问多维数组输入
- 读取文件并将其作为整型数组输入
- 从c++文件中获取输入(矩阵数组输入)
- 数组输入不工作
- 函数结构数组输入cin问题
- 结束数组输入(c++行业标准)