简体   繁体   中英

Initializing a const variable by reading its value from file (C++)

I am writing a code where two varibales are constants but they need to be read from a.txt file.

I have written the function

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();
}

Obviously I cannot add the const specifier in the prototype. What I do is the following:

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

Is there a better way?

You could modify ReadValues a little to return the 2 double s as a 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};
}

and now you can make your variables const like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM