c++ – How to detect an error while typing from istream_iterator<int>

Question:

I want to populate a vector from cin std::istream_iterator using std::istream_iterator . There is a code like this:

#include<iostream>
#include<iterator>
#include<vector>

int main()
{
  std::istream_iterator< int > in(std::cin);
  std::istream_iterator< int > end;
  typedef std::vector< int > int_vector;
  int_vector data;
  std::back_insert_iterator< int_vector > target(data);
  while (in != end)
  {
    *target = *in;
    ++in;
    ++target;
  }
  std::ostream_iterator<int> out(std::cout, ", ");
  std::copy(data.begin(), data.end(), out);
  return 0;
}

Hence two questions :

  1. How do I complete input correctly?
  2. How to solve the problem with incorrect input (not int , but double for example)?

Answer:

in == end at the end of input (EOF) or if any input error has occurred. Therefore, if your cycle ends prematurely, it means that an error has occurred. It can be found by checking if the input has reached the end: cin.eof() :

#include <iostream>
#include <iterator>
#include <vector>

int main() {
  std::istream_iterator<int> numbers { std::cin  }, eof;

  // populate vector
  std::vector<int> v;
  std::copy(numbers, eof, std::back_inserter(v));

  // print vector
  std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n"));
  return !std::cin.eof(); // success on eof
}

An example .

Which is equivalent to:

#include <iostream>
#include <iterator>
#include <vector>

int main() {
  // populate vector
  std::vector<int> v;
  for (int n; std::cin >> n; )
    v.push_back(n);

  // print vector
  for (int n : v)
    std::cout << n << '\n';

  return !std::cin.eof(); // success on eof
}

Example .

Scroll to Top