ifstream的operator>>如何检测行末?

7

我有一个不规则列表,其中数据看起来像这样:

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

请注意,某些行有2个数字,而某些行有3个数字。 目前我的输入代码看起来像这样
inputFile >> a >> b >> c;

然而,我希望它可以忽略只有2个数字的行,是否有简单的解决方法?(最好不使用字符串操作和转换)谢谢
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
        }
    }
}

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

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!
      }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接