【发布时间】:2026-02-01 16:10:01
【问题描述】:
当我熟悉 C++ 的 I/O 方面时,我正在尝试编写一个程序来从 std::cin 读取一些整数行。假设输入如下所示:
1 2 3
4 5 6
7 8 9
10 11 12
如何将上述行读入二维向量?
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}
}
*/
我还尝试将上述整数行读取为一维向量,但在处理 '\n' 字符时遇到了一些问题。我的代码是:
string rawInput;
vector<int> temp;
while(getline(cin, rawInput, ' ') ){
int num = atoi( rawInput.c_str() );
temp.push_back(num);
}
我通过打印出“temp”向量中的所有元素得到的最终结果是:
1 2 3 5 6 8 9 11 12 // 4, 7, 10 went missing
感谢任何帮助。谢谢。
【问题讨论】:
-
你可以用
atoi(x.c_str())代替stoi(x)。
标签: c++