I need to read an unknown number of inputs using either C++ or Java. Inputs have exactly two numbers per line. I'd need to use cin or a System.in Scanner because input comes from the console, not from a file.
Example input:
1 2
3 4
7 8
100 200
121 10
I want to store the values in a vector. I have no idea how many pairs of numbers I have. How do I design a while loop to read the numbers so I can put them into a vector?
You can use an idiomatic std::copy in C++: (see it work here with virtualized input strings)
std::vector<int> vec;
std::copy (
std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(vec)
);
That way, it will append onto the vector each time an integer is read from the input stream until it fails reading, whether from bad input or EOF.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With