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

标签 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;
}

但是如果我放置 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/

相关文章:

c++ - Qpushbutton 图标出现在实际按钮的左侧,如何居中或拉伸(stretch)它?

c++ - header 守卫仍然会产生重新定义错误

c++ - 将 STL 容器<T *> 转换为容器<T const *>

c++ - 读取PNG header 的宽度和高度

c++ - 尝试创建大小未知的模板类的二维数组 (C++)

谁能解释一下,这个结构初始化实际上是如何工作的?

c++ - 连接按下的 WM_Char 键值 win32API

Enthought Canopy 中的 Python 文件 open() 失败并显示 : "IOError No such file or directory"

c++ - 读取整个文件,然后在同一个 std::fstream 中覆盖所有文件

ios - 使用 UIImageView repeatedValue() 初始化 Swift 数组似乎不起作用