【问题标题】:ifstream's operator>> to detect end of line?ifstream 的 operator>> 来检测行尾?
【发布时间】:2011-10-14 13:57:42
【问题描述】:

我有一个不规则的列表,其中的数据如下所示:

[Number] [Number]
[Number] [Number] [Number] 
[Number] [Number] [Number] 
[Number] [Number] [Number] 
[Number] [Number] [Number] 
[...]

请注意,有些行有 2 个数字,有些行有 3 个数字。 目前我的输入代码如下所示

inputFile >> a >> b >> c;

但是,我想忽略只有 2 个数字的行,是否有一个简单的解决方法? (最好不使用字符串操作和转换)

谢谢

【问题讨论】:

    标签: c++ parsing operator-overloading ifstream istream


    【解决方案1】:
    std::string line;
    while(std::getline(inputFile, line))
    {
          std::stringstream ss(line);
          if ( ss >> a >> b >> c)
          {
               // line has three numbers. Work with this!
          }
          else
          {
               // line does not have three numbers. Ignore this case!
          }
    }
    

    【讨论】:

      【解决方案2】:

      使用getline,然后分别解析每一行:

      #include <iostream>
      #include <sstream>
      #include <string>
      
      int main()
      {
          std::string   line;
          while(std::getline(std::cin, line))
          {
              std::stringstream linestream(line);
              int a;
              int b;
              int c;
              if (linestream >> a >> b >> c)
              {
                  // Three values have been read from the line
              }
          }
      }
      

      【讨论】:

        【解决方案3】:

        我能想到的最简单的解决方案是使用std::getline 逐行读取文件,然后将每一行依次存储在std::istringstream 中,然后对其执行&gt;&gt; a &gt;&gt; b &gt;&gt; c 并检查返回值。

        【讨论】:

          猜你喜欢
          • 2010-10-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多