Reading all values from one variable with ifstream

I am in search of how to read all values from one variable in a file.
Say a file called items.txt and I want to read all the int size
from this file. How can I do that? I'm just used to it this way:

1
2
3
4
  ifstream read("items.txt");
  while(read >> size){
       std::cout << size;
  }


But what if I want to make some total size out from all the sizes instead
of just printing out all the size values from a file? How could I get all
the values to create a int totalSize; out from these?

Thanks in advance!
1
2
3
   int size, totalSize = 0;
   ifstream read("items.txt");
   while ( read >> size ) totalSize += size;


You could probably use std::accumulate() with a stream iterator as well.
Last edited on
That doesn't work for me :/ It just returns 0 in that case
Last edited on
Check:
(a) That the file opened (e.g. assert(read) or read.good() or !read.fail() )
(b) That it contained anything (just look)
(c) That it only contained ints

Post minimal compileable code that reproduces this error; also post your input file.
Last edited on
Topic archived. No new replies allowed.