Reading input from file into vector

Apr 12, 2019 at 8:00pm
Hello,

I was reading in Bjarne Stroustrup's "Principle and Practice Using C++" when I encountered the following example, where we are reading from a file.

1
2
3
4
5
0 60.7
1 60.6
2 60.3
3 59.22
q


1
2
3
4
5
6
7
8
9
10
struct Reading {
int hour;
double temperature;

ifstream ist{"filename.txt"};
vector<Reading> temps; //store readings here
int hour;
double temperature;
while (ist >> hour >> temperature) //when exactly does this terminate?? When there is no longer an int and a double per line?
temps.push_back(Reading{hour, temperature});


I am also wondering about the syntax of adding instances of the Reading-struct to the vector. Like, usually when I work with classes I would write like this

 
MyDummyClass m{1,2,3};


where as in Bjarne's example it is kinda given as(i.e. he just writes the struct name and then gives the values, without explicitly creating a Reading object if that makes sense..?)
 
MyDummyClass{1,2,3};

What is the difference between the two?
Last edited on Apr 12, 2019 at 8:01pm
Apr 12, 2019 at 8:07pm
In the first you are providing an identifier with which to make future references to your newly-constructed object.

1
2
3
MyDummyClass m{1,2,3};
…
m.foo();

In the second you only need the object to exist long enough to be used as argument to a function. Hence, it does not need a name.

 
myfunction( MyDummyClass{1,2,3} );

The only difference is whether or not you provide a name. (You cannot provide a name in a function’s actual argument list, BTW.)

Hope this helps.
Apr 12, 2019 at 8:15pm
Thanks!

Can you do like this? I don't think it'll work, but worth asking...
1
2
3
4
5
6
MyDummyClass m{1,2,3};
myfunction(m)

//instead of 

myfunction(MyDummyClass{1,2,3})


and do you know the answer of my first question, in line #9 in the code I posted?
Apr 12, 2019 at 8:31pm
Sure, that’ll work just fine.

Line #9: it terminates when either of the two input attempts fail and set the stream state to not good() (one or more of fail(), bad(), or eof()).
Apr 12, 2019 at 9:38pm
But will it still work inside a while loop? Thought I'd get "redefinition of m" issues.
Apr 12, 2019 at 10:26pm
1
2
3
4
5
6
Zeta z;

…


anytype z; // redefinition of z 

vs
1
2
3
4
5
6
for (…)
{
  Zeta z;
  …
}
// where is the other definition of z? 

Hope this helps.

[edit]
Every { and } declare a scoped block. So the z technically goes out of scope at the end of the block and is destroyed. Hence:

1
2
3
4
5
6
for (…)
{
  Zeta z;
  …
}
int z; // legal, no other z in current scope 
Last edited on Apr 12, 2019 at 10:28pm
Topic archived. No new replies allowed.