在单行上用空格分隔多个输入
Space separated multiple inputs on single line
5 1256 4323 7687 3244 5678
2 2334 7687
5 2334 5678 6547 9766 9543
我应该以上述形式输入。每行的第一个整数决定后面整数的数量。由于第一个整数可以变化,我不知道是否可以使用'scanf'。
当然,您可以对scanf
执行如下操作。
while (scanf("%d", &n) == 1) {
row++;
for (col = 0; col < n; col++)
scanf("%d", &a[row][col]);
}
这与cin
非常相似:
while (cin >> n) {
row++;
for (col = 0; col < n; col++)
cin >> a[row][col];
}
一个更具体的例子,假设输入是N
的最大行数
int** a = new int*[N];
int row = -1; // not started yet
while (cin >> n) {
row++;
a[row] = new int[n];
for (int col = 0; col < n; col++)
cin >> a[row][col];
}
如果事先不知道N
,我们也可以这样使用std::vector
。
vector<vector<int> > a;
while (cin >> n) {
vector<int> line(n);
for (int col = 0; col < n; col++)
cin >> line[col];
a.push_back(line);
}
我永远不会明白为什么你不想在Stackoverflow.com上搜索!这个问题得到了多次回答。例如-
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
int main()
{
std::ifstream data("test.txt");
std::string line;
while(std::getline(data,line))
{
std::stringstream lineStream(line);
std::string cell;
while(std::getline(lineStream,cell,' '))
{
std::cout<<cell<<std::endl;
}
}
}
相关文章:
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- C++逗号分隔的输入数组代码过早退出
- 获取带有字符 X 的输入 X/X/etc 并用斜杠 / 分隔它
- 获取由空格分隔的未知大小的单行输入,并将其存储到整数数组中
- 如果用户输入两个或多个由空格分隔的字符串C++如何防止缓冲区溢出?
- 使用运算符将分隔的输入分隔>>变量
- 来自 2 个不同向量的输入,用逗号分隔
- 如何将输入重定向与特殊整数作为分隔线和直至EOF
- 按标记分隔输入
- 如何在用空格分隔的行中获得无限的输入
- 我如何使用CIN输入整数,每个数字都被逗号分隔
- 如何使用符号分隔字符串而不是空格的输入字符串流
- C++:如何输入用逗号(,)分隔的值
- 以C++分隔用户输入的时间
- 如何读取用户输入的逗号分隔整数
- 在 cpp 中使用 getline 输入数组中的空格分隔数字
- 如何从用冒号分隔的cin中获取输入
- 分隔输入C++
- 如何在 c++ 中读取带有分隔字符的用户输入,同时保留空格作为输入
- 如何通过空格将一个输入分隔为多个输入