我必须在我的 C++ 代码中定义一个全局数组,它的大小必须从文件中读取。我正在使用下面的代码
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
string inputfile = "input.txt";
ifstream infile(inputfile.c_str());
infile>>N; // N = size of Array
int array[N];
// ------some code here-----
int main(){
int N;
cout << N<<endl;
return 0;
}
但是如果我放置 3 行
string inputfile = "input.txt";
ifstream infile(inputfile.c_str());
infile>>N; // N = size of Array
在主循环中这段代码有效。不幸的是,我不能将它放在任何函数中,因为我需要从变量 N 初始化一个全局数组。
我问过很多人并搜索过不同的地方,但我似乎无法弄清楚。感谢您的帮助。
最佳答案
数组的大小必须是常量表达式,即在编译时已知。
从文件中读取值本质上是动态操作,发生在运行时。
一种选择是使用动态分配:
int array_size()
{
int n;
ifstream infile("input.txt");
if (infile>>n)
return n;
else
throw std::runtime_error("Cannot read size from file");
}
int* array = new int[array_size()];
不过最好用std::vector<int>
代替数组可以动态调整大小。
关于c++ - 从文件输入 C++ 定义全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25528953/