通过从文件中读取其值来初始化 const 变量(C++)

时间:2021-01-28 07:15:56

标签: c++ file constants

我正在编写一个代码,其中两个变量是常量,但它们需要从 .txt 文件中读取。

我已经写好了函数

void ReadValues(const char filename[],double& sig,double& tau)
{
  std::ifstream infile;
  infile.open(filename);
  if(!infile.is_open())
    {
      std::cout << "File is not open. Exiting." << std::endl;
      exit(EXIT_FAILURE);
    }
  while(!infile.eof())
    infile >> sig >> tau;

  infile.close();
}

显然我不能在原型中添加 const 说明符。我做的是以下内容:

double s,t;
ReadValues("myfile.txt",s,t);
const double S = s;
const double T = t;

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以稍微修改 ReadValues 以将 2 个 double 作为 pair 返回。

auto ReadValues(const char filename[]) -> std::pair<double, double>
{
  double sig, tau;  // local variable instead of reference parameters
  // read from file into sig and tau
  return {sig, tau};
}

现在您可以像这样设置变量 const

auto const [S, T] = ReadValues("myfile.txt");
相关问题