How to read groups of integers from a file, line by line in C++

It depends on whether you want to do it in a line by line basis or as a full set. For the whole file into a vector of integers:

int main() {
   std::vector<int> v( std::istream_iterator<int>(std::cin), 
                       std::istream_iterator<int>() );
}

If you want to deal in a line per line basis:

int main()
{
   std::string line;
   std::vector< std::vector<int> > all_integers;
   while ( getline( std::cin, line ) ) {
      std::istringstream is( line );
      all_integers.push_back( 
            std::vector<int>( std::istream_iterator<int>(is),
                              std::istream_iterator<int>() ) );
   }
}

Leave a Comment