Jump to content
  • Advertisement
Sign in to follow this  
V3rt3x

[STL] reading from file to a vector

This topic is 4779 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I want to read a known number of integers from a file into a vector<int>. I would like to know if there is a way like this:
std::vector<int> v;
std::ifstream file( "ints.dat" );

std::istream_iterator<int> start( file );
std::istream_iterator<int> end;
std::copy( start, end, v.begin() );
but for a given number of integers, not reading the entire file? Or reading until the end of the current line. How to adjust the end iterator?

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by V3rt3x
I want to read a known number of integers from a file into a vector<int>. I would like to know if there is a way like this:
*** Source Snippet Removed ***

but for a given number of integers, not reading the entire file? Or reading until the end of the current line. How to adjust the end iterator?


There's a copy_n algorithm:

std::vector<int> v;
std::ifstream file( "ints.dat" );

std::istream_iterator<int> start( file );
std::istream_iterator<int> end;

int how_many = 5;//However many

std::copy_n( start, how_many, v.begin() );


I don't know what this would do if there weren't enough integers in the file, though.


Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Just a warning -- copy_n is NOT currently part of the standard library.

It's pretty trivial to implement though.

namespace ext {

template <typename in_iter, typename out_iter>
std::pair<in_iter,out_iter> copy_n(in_iter b, size_t n,
out_iter o) {
while ( n-- > 0 ) *o++ = *b++;
return std::make_pair( n, o );
}

} // namespace ext



And I think that an istream_iterator will give an arbitrary value if it goes on past the end and not fail unless the corresponding exceptions() flag(s) are set in the istream you're using ( since istream_iterators use operator>>, iirc ).

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!