2013-01-18 24 views
0

我想设置一个字符串数组,其大小和内容取决于用户输入。我得到一个错误声明我的数组,它说大小的变量不是正确的类型。我花了几个小时就想我会问。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];

+2

变量不能用作数组大小,您必须使用编译时常量。你想要的是'std :: vector',一个运行时可调整大小的数组类。 –

+0

请发布您正在收到的确切错误。 –

回答

3

数组需要有它的大小编译时间值。你的代码不会编译,因为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; 
} 
+0

我如何使用?新的进口? – user1807880

+0

@ user1807880刚刚编辑。 –

2

您可以用这种方式宣告您的namesArray:

string * namesArray = new string[a]; 

这应该工作,因为它基于输入值动态分配内存。

但是当然,最好是用vector来代替。如果使用vector,则不需要删除数组。

+0

但是,您需要小心以确保它永远不会超出范围以防止内存泄漏。由于它主要是,这不应该是一个问题。 – brandonsbarber

+0

非常感谢! – user1807880

0

不能使用变量作为静态intiailised数组的大小,要做到这一点,你需要动态分配的数组,像

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; 
} 
0

正如马克说,这是一个编译时问题。您可以使用vector,但另一种方法可以为阵列动态分配内存。这意味着使用关键字new

所以,你的代码将string* namesArray = new string[a];

使用new返回一个指针数组,所以相应的调整。

相关问题