我需要创建一个程序,用户输入所需的数组大小,然后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),我会收到错误:
表达式必须具有常量值
知道为什么会这样吗?
答案 0 :(得分:5)
C ++没有variable-length arrays。有些编译器虽然实现了扩展,但它仍然不是C ++语言的标准功能,而且不可移植。
如果您想要一个运行时变量长度数组,请使用std::vector
代替:
std::vector<int> flex_array(count);