C++ cin 读取 STDIN
如何使用C++获取所有STDIN
并解析它?
例如,我的输入是
2
1 4
3
5 6 7
我想使用 C++ 使用 cin 读取 STDIN 并将每一行存储在数组中。因此,它将是一个向量/整数数组的数组。
谢谢!
How to use C++ to get all the STDIN
and parse it?
For example, my input is
2
1 4
3
5 6 7
I want to use C++ to read the STDIN
using cin and store the each line in an array. So, it will be an vector/array of array of integers.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于这没有标记为作业,因此这里有一个使用
std::vector
和std::stringstream
读取stdin
的小示例。我在最后添加了一个额外的部分,用于迭代向量并打印出值。给控制台一个EOF
(ctrl + d for *nix, ctrl + z 对于 Windows)以阻止其读取输入。输入/输出:
编辑:向代码添加了更多注释。另请注意,可以将
int
的空向量
添加到vecLines
(来自空输入行),这是故意的,以便输出与输入相同。Since this isn't tagged as homework, here's a small example of reading from
stdin
usingstd::vector
s andstd::stringstream
s. I added an extra part at the end also for iterating through thevector
s and printing out the values. Give the console anEOF
(ctrl + d for *nix, ctrl + z for Windows) to stop it from reading in input.Input/Output:
EDIT: Added a couple more comments to the code. Also note that an empty
vector
s ofint
s can be added tovecLines
(from an empty line of input), that's intentional so that the output is the same as the input.抱歉,我只是不确定是否还有比这更好的方法。
Sorry, I just wasn't sure if there's any way better than this.
这个应该符合您的要求,使用
istringstream
将行分隔成数组。This one should fit your requirement , use
istringstream
to separate the line into an array.