Kate Kate - 2 months ago 12
C++ Question

How to input int, vector of int, int and vector of string correctly

I try to input 2 numbers (int) and 2 vectors (int, string):

int N_num;
int N_dir;
vector<int> v;
vector<string> v1;
std::cin >> N_num;
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),std::back_inserter(v));
std::cin >> N_dir;
std::copy(std::istream_iterator<string>(std::cin),
std::istream_iterator<string>(), std::back_inserter(v1));


My input is:

3
1 4 5
4
T M M R


Then I cout N_dir (= 4), and get -858993460 as an output. My guess is that the first vector input does not terminate when I input "4" to N_dir. How do I stop inputting a vector and go to the next variable?

Answer

The problem is that the first std::copy call will read the 4 that is supposed to be read into N_dir. So when you attempt to read into N_dir you read the first string instead and the input operation will fail and not initialize N_dir, leaving it indeterminate.

Use std::copy_n instead:

std::copy_n(std::istream_iterator<int>(std::cin), N_num,
            std::back_inserter(v));