Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading an unknown number of inputs

Tags:

java

c++

input

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?

like image 996
tianz Avatar asked Dec 06 '25 04:12

tianz


1 Answers

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.

like image 188
chris Avatar answered Dec 08 '25 16:12

chris