gpt4 book ai didi

C++:从 cin 中读取整数行

转载 作者:行者123 更新时间:2023-11-28 05:45:09 25 4
gpt4 key购买 nike

当我熟悉 C++ 的 I/O 方面时,我正在尝试编写一个程序来从 std::cin 中读取一些整数行。假设输入如下所示:

1 2 3
4 5 6
7 8 9
10 11 12

如何将上面的行读入二维 vector ?

vector<vector<int>> nums;
/*
... some code here and nums will look like the following:
nums = {
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
}
*/

我也尝试将上面的整数行读入一维 vector ,但我在处理“\n”字符时遇到了一些问题。我的代码是:

string rawInput;
vector<int> temp;
while(getline(cin, rawInput, ' ') ){
int num = atoi( rawInput.c_str() );
temp.push_back(num);
}

我通过打印出“temp” vector 中的所有元素得到的最终结果是:

1 2 3 5 6 8 9 11 12   // 4, 7, 10 went missing

感谢任何帮助。谢谢。

最佳答案

首先使用 getline 抓取整行,然后你可以使用 istringstream 创建 int 的流仅适用于该行。

到那时,只需使用带有两个迭代器的 vector 构造函数创建每个整数子 vector 即可。一个 istream_iterator<int> 在你的 istringstream完成这个:

std::vector<std::vector<int>> nums;
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream ss(line);
nums.emplace_back(std::istream_iterator<int>{ss}, std::istream_iterator<int>{});
}

关于C++:从 cin 中读取整数行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36365202/

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