Read in parameters from file with specified format

Hi,

I have a problem reading parameters from a file with a certain format.
Say, in my Program I have an Integer variable a, one double variable b, and one
c++ string c.

Now I would like to initialize these with with the values given in
a file with the following format:

a = 10
b = 3.141
c = Schokoladenkuchen

How would I do this?

Hope somebody can help...


Here is some hideous code that will work with that exact file layout. From here, you can make it much smarter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
ifstream inFile("filename.txt");

string ignore;
int a;
double b;
string c;

inFile >> ignore;
inFile >> ignore;
inFile >> a;

inFile >> ignore;
inFile >> ignore;
inFile >> b;

inFile >> ignore;
inFile >> ignore;
inFile >> c;
Last edited on
Thanks a lot for your answer. I haven't been programming for that long yet. What kind of things could you
do to make it smarter?

Maybe anybody else got some ideas?

Is there maybe a way to store a, b and c in some kind of abstract array?

Then you could do some kind of loop, preventing rewriting those 3 "inFile" lines over and over...
Then you could do some kind of loop

Sounds like you're describing a function.

A templated function would do well:

1
2
3
4
5
6
7
template <class T>
  void readIn (ifstream& inStream, T& valToPopulate) {
  string ignore;
  inStream >> ignore;
  inStream >> ignore;
  inStream >> valToPopulate;
}
Last edited on
Thanks, that looks good!
Topic archived. No new replies allowed.