gpt4 book ai didi

java - 读取未知数量的输入

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:19:30 25 4
gpt4 key购买 nike

我需要使用 C++ 或 Java 读取未知数量的输入。输入每行恰好有两个数字。我需要使用 cinSystem.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com