在单行上用空格分隔多个输入

Space separated multiple inputs on single line

本文关键字:输入 分隔 空格 单行      更新时间:2023-10-16
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;
    }
  }
}