如何使用C++获取所有STDIN并对其进行解析?

例如,我的输入是

2
1 4
3
5 6 7

我想使用C++使用cin读取STDIN并将每一行存储在一个数组中。因此,它将是整数数组的 vector /数组。

谢谢!

最佳答案

由于这没有被标记为作业,因此这是一个使用stdinstd::vectorstd::stringstream读取的小示例。我在末尾添加了一个额外的部分,用于遍历vector并打印出值。给控制台输入EOF(对于* nix,为ctrl + d;对于Windows,为ctrl + z),以阻止其读取输入。

#include <iostream>
#include <vector>
#include <sstream>

int main(void)
{
   std::vector< std::vector<int> > vecLines;

   // read in every line of stdin
   std::string line;
   while ( getline(std::cin, line) )
   {
      int num;
      std::vector<int> ints;
      std::istringstream ss(line); // create a stringstream from the string

      // extract all the numbers from that line
      while (ss >> num)
         ints.push_back(num);

      // add the vector of ints to the vector of vectors
      vecLines.push_back(ints);
   }

   std::cout << "\nValues:" << std::endl;
   // print the vectors - iterate through the vector of vectors
   for ( std::vector< std::vector<int> >::iterator it_vecs = vecLines.begin();
         it_vecs != vecLines.end(); ++it_vecs )
   {
      // iterate through the vector of ints and print the ints
      for ( std::vector<int>::iterator it_ints = (*it_vecs).begin();
         it_ints < (*it_vecs).end(); ++it_ints )
      {
         std::cout << *it_ints << " ";
      }

      std::cout << std::endl; // new line after each vector has been printed
   }

   return 0;
}

输入输出:
2
1 4
3
5 6 7

Values:
2
1 4
3
5 6 7

编辑:向代码添加了更多注释。还要注意,可以将vector的空int s添加到vecLines(从输入的空行),这是有意使输出与输入相同的。

10-08 08:21
查看更多