我需要使用 C++ 或 Java 读取未知数量的输入。输入每行恰好有两个数字。我需要使用 cin
或 System.in
Scanner
,因为输入来自控制台,而不是文件。
示例输入:
1 2
3 4
7 8
100 200
121 10
我想将值存储在 vector 中。我不知道我有多少对数字。如何设计一个 while
循环来读取数字,以便将它们放入 vector 中?
最佳答案
您可以在 C++ 中使用惯用的 std::copy
:( 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)
);
这样,每次从输入流中读取整数时,它都会追加到 vector 上,直到读取失败,无论是来自错误输入还是 EOF。
关于java - 读取未知数量的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12720133/