Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

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?

question from:https://stackoverflow.com/questions/65932546/initializing-a-const-variable-by-reading-its-value-from-file-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could modify ReadValues a little to return the 2 doubles 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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...