Reading an std::ifstream to a vector of lines?

I suspect you want something like this: include #include #include std::vector out; std::ifstream fs("file. Txt"); std::copy( std::istream_iterator(fs), std::istream_iterator(), std::back_inserter(out)).

I suspect you want something like this: #include #include #include std::vector out; std::ifstream fs("file. Txt"); std::copy( std::istream_iterator(fs), std::istream_iterator(), std::back_inserter(out)).

Perfect! Thanks! – Austin Hyde Nov 4 '09 at 17:58 1 You should note that it will not detect errors in the input file (ie two numbers on the same line).

– Loki Astari Nov 4 '09 at 18:57 A stream iterator will read multiple values from a single line, separated by whitespace, but it will stop if something other than a digit or whitespace is encountered, leaving the stream with fs.eof() == false and fs.fail() == true. – Tim Sylvester Nov 4 '09 at 19:28.

The standard iterators as describe by 'Tim Sylvester' is the best answer. But if you want a manual loop then, Just to provide a counter example too: 'jamuraa' vector ifstream_lines(ifstream& fs) { vector out; int temp; while(fs >> temp) { // Loop only entered if the fs >> temp succeeded. // That means when you hit eof the loop is not entered.

// // Why this works: // The result of the >> is an 'ifstream'. When an 'ifstream' // is used in a boolean context it is converted into a type // that is usable in a bool context by calling good() and returning // somthing that is equivalent to true if it works or somthing that // is equivalent to false if it fails. // out.

Push_back(temp); } return out; }.

Std::getline(stream, var) reads into a std::string for var. I suggest using the stream operators to read into the int instead, and check for errors if needed: vector ifstream_lines(ifstream& fs) { vector out; int temp; while (!(fs >> temp).fail()) { out. Push_back(temp); } fs.

Seekg(0,ios::beg); fs.clear(); return out; }.

That's horrible. Never test for eof() in the condition. It is ALWAYS better to test the action in the condition.

– Loki Astari Nov 4 '09 at 18:09.

The result of the >> is an 'ifstream'. // is equivalent to false if it fails.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions