使用C ++中的用户输入变量声明数组大小。在不同的IDE中有不同的结果?

时间:2016-12-02 09:30:01

标签: c++ arrays vector visual-studio-2015 codeblocks

我需要创建一个程序,用户输入所需的数组大小,然后C ++代码创建它,然后允许数据输入。

这适用于Code Blocks IDE,但不适用于Visual Studio Community 2015

当我在CodeBlocks版本13.12中放入以下代码时,它可以正常工作

#include<iostream>
using namespace std;

int main()
{
    int count;
    cout << "Making the Array" << endl;
    cout << "How many elements in the array " << endl;
    cin >> count;
    int flex_array[count];
    for (int i = 0; i < count; i = i + 1)
    {
        cout << "Enter the " << i << " term " << endl;
        cin >> flex_array[i];
    }

    for (int j = 0; j < count; j = j + 1)
    {
        cout << "The " << j << " th term has the value " << flex_array[j] << endl;
    }
    return 0;
}

但是,如果我在Visual Studio 2015中输入相同的代码(即版本14.0.25425),我会收到错误:

  

表达式必须具有常量值

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:5)

C ++没有variable-length arrays。有些编译器虽然实现了扩展,但它仍然不是C ++语言的标准功能,而且不可移植。

如果您想要一个运行时变量长度数组,请使用std::vector代替:

std::vector<int> flex_array(count);