从文件输入C++定义全局变量

use*_*865 1 c++ file-io initialization

我必须在我的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;
}
Run Code Online (Sandbox Code Playgroud)

但如果我放置3条线

string inputfile = "input.txt";
ifstream infile(inputfile.c_str());
infile>>N; // N = size of Array
Run Code Online (Sandbox Code Playgroud)

在主循环内部,此代码有效.不幸的是我不能把它放在任何函数中,因为我需要从变量N初始化一个全局数组.

我问了很多人并搜索了不同的地方,但我似乎无法弄清楚这一点.谢谢你的帮助.

Jon*_*ely 6

数组的大小必须是常量表达式,即在编译时已知.

从文件中读取值是一种固有的动态操作,在运行时发生.

一种选择是使用动态分配:

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()];
Run Code Online (Sandbox Code Playgroud)

但是,更换std::vector<int>可以动态调整大小的数组会更好.