C ++ cin读取STDIN

时间:2011-12-25 01:23:31

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

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

例如,我的输入是

2
1 4
3
5 6 7

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

谢谢!

3 个答案:

答案 0 :(得分:4)

由于这不是标记为家庭作业,因此这里有一个使用stdinstd::vector来自std::stringstream的小例子。我在最后添加了一个额外的部分,用于迭代vector并打印出值。为控制台提供EOF ctrl + d 用于* 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 

编辑:在代码中添加了更多评论。另请注意,可以将vector的{​​{1}}空int添加到vecLines(来自空行的输入),这是有意的,因此输出与输入。

答案 1 :(得分:0)

int main () 
{
    char line[100];
    while(!cin.eof()){
        cin.getline(line, 100);
        printf("%s\n", line);
    }

    return 0;
}

对不起,我只是不确定是否有比这更好的方法。

答案 2 :(得分:0)

这个应该符合您的要求,使用istringstream将行分成一个数组。

#include <iostream>
#include <vector>
#include <sstream>
#include <string>
using namespace std;

int main()
{
        string s("A B C D E F G");
        vector<string> vec;
        istringstream iss(s);

        do
        {
                string sub;
                iss >> sub;
                if ( ! sub.empty() ) 
                        vec.push_back (sub);
        } while (iss);

        vector<string>::iterator it = vec.begin();
        while ( it != vec.end() )
        {
                cout << *it << endl;
                it ++;
        }

        return 0;
}
相关问题