C++ cin 读取 STDIN

标签 c++ visual-c++ input stdin cin

如何使用C++获取所有STDIN并解析它?

例如,我的输入是

2
1 4
3
5 6 7

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

谢谢!

最佳答案

由于这没有标记为作业,因此这里有一个使用 std::vectorstd::stringstream 读取 stdin 的小示例s。我在最后添加了一个额外的部分,用于迭代 vector 并打印出值。给控制台一个 EOF (ctrl + d for *nix, ctrl + z 对于 Windows)以阻止其读取输入。

#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 

编辑:向代码添加了更多注释。另请注意,可以将 int 的空 vector 添加到vecLines(来自空输入行),这是故意的,以便输出与输入相同。

关于C++ cin 读取 STDIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8627784/

相关文章:

html - &lt;input type ='button'/> 和 &lt;input type ='submit'/> 的区别

javascript - 当选择单选框时向输入字段添加属性

C++ .find() 函数在目录中搜索文件名

c++ - 是否可以在Windows XP下用普通的C++程序覆盖代码段?

c++ - 为什么编译器不能优化这两条语句?

c - scanf 中的 %[^\n]s 不等待输入并被跳过

c++ - 获取指定格式的数字时区

c++ - 二进制反转为十进制数

c++ - 如何在 CRT 中模拟文件读取错误

c++ - Cryptopp.dll访问冲突读取位置0x74736554