c++声明一个基于用户输入的内容和大小的字符串数组

C++ declare a string array with content and size based on user input

本文关键字:数组 输入 字符串 声明 一个 c++ 于用户 用户      更新时间:2023-10-16

我试图建立一个字符串数组,其大小和内容取决于用户的输入。我得到一个错误声明我的数组,它说变量的大小不是正确的类型。我花了几个小时在这个问题上,只是想问一下。

下面是我的代码:

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