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>() ) );
   }
}

You could do smtng like this(I used cin, but you can use any other file stream):

string line;
while( getline( cin, line ) )
{
 istringstream iss( line );
 int number;
 while( iss >> number )
  do_smtng_with_number();
}

Or:

int number;
while( cin >> number )
{
 do_smtng_with_number();
}

What result do you want? If you want all the integers in a single vector, you could do something like:

std::ifstream input("input.txt");

std::vector<int> data(std::istream_iterator<int>(input),
                      std::istream_iterator<int>());

That discards the line-structure though -- you end up with the data all together. One easy way to maintain the original line structure is to read a line with getline, initialize a stringstream with that string, then put the values from that stringstream into a vector (and push that onto the back of a vector of vectors of int).

std::vector<std::vector<int> > data;
std::vector<int> temp;

std::string t;
while (std::getline(input, t)) {
    std::istringstream in(t);
    std::copy(std::istream_iterator<int>(in), 
              std::istream_iterator<int>(), 
              std::back_inserter(temp);
    data.push_back(temp);
}

Tags:

C++

Input