7

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

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

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

inputFile >> a >> b >> c;

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

谢谢

4

3 回答 3

13

使用 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
        }
    }
}
于 2011-07-27T19:43:49.243 回答
4

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

于 2011-07-27T19:41:31.193 回答
2
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!
      }
}
于 2011-07-27T19:44:47.793 回答