c++ - ifstream 的 operator>> 来检测行尾?

标签 c++ parsing operator-overloading ifstream istream

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

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

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

inputFile >> a >> b >> c;

但是,我想让它忽略只有 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
        }
    }
}

关于c++ - ifstream 的 operator>> 来检测行尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6850246/

相关文章:

parsing - Bison 语法中的浮点被截断

python - PLY中双括号的含义

python - 为什么 Python 有一个 __ne__ 运算符方法而不仅仅是 __eq__?

c++ - 在 C++ 中是否必须通过引用传递类

c++ - SFML 停止或删除时钟

c++ - 如何将图标添加到您的 C++ 控制台应用程序?

c++ - Qt 中的事件处理

c++ - 指向 std::vector 的指针

c# - 将文本文件解析为字典

c++ - 程序没有调用正确的重载运算符