跳过输入流值

Excelcius

是否有任何简单的机制可以跳过直到带有C ++输入流的下一个空格(如ifstream)?

我知道ignore如果要跳过多少个字符或期望使用什么定界符,就可以使用但是,IMO通常在不提供任何其他参数的情况下仅读取下一个空白ignore使用它是丑陋的operator>>我也可以使用假人,但这只会使情况变得更糟。

例子

auto importantInfo1 = 0;
auto importantInfo2 = 0;
auto someDummy = 0; // This is ugly and doesn't clearly express the intent

file >> importantInfo1 >> someDummy >> importantInfo2;

同样,在某些情况下,如果我需要在“跳过”情况下处理不同的数据类型,我将需要多个虚拟对象。

我会想象这样的事情:

file >> importantInfo1;
file.skip<int>(1);
file >> importantInfo2;

甚至更好:

auto importantInfo1 = 0;
auto importantInfo2 = 0;

file >> importantInfo1 >> skip<int> >> importantInfo2;

我想这样一种解决方案比不需要时将其实际解析和存储在某个地方的性能还要好。

可能的解决方案

使用提供的答案制定了此解决方案。它基本上与接受的答案相同,但是不需要临时的。而是,它跳过第一个空格,然后跳过除空格以外的任何字符,直到再次到达空白为止。此解决方案可以使用2个while循环,但无需了解提取的类型。我并不是说这是一个高性能的解决方案,也不是什么花哨的方法,但是它会使生成的代码更短,更简洁,更富有表现力。

template<typename CharT, typename Traits>
inline std::basic_istream<CharT, Traits>& skip(std::basic_istream<CharT, Traits>& stream)
{
    while (stream && std::isspace(stream.peek())) stream.ignore();
    while (stream && !std::isspace(stream.peek())) stream.ignore();
    return stream;
}
用户名

我认为您的想法是有一个操纵器来跳过数据是正确的方法。

跳过“琐碎”的数据:

#include <sstream>

template<typename T, typename Char, typename Traits>
inline std::basic_istream<Char, Traits>& skip(std::basic_istream<Char, Traits>& stream) {
    T unused;
    return stream >> unused;
}

int main()
{
    std::istringstream in("1 666 2 ");
    int a;
    int b;
    in >> a >> skip<int> >> b;
    std::cout << a << b << '\n';
}

如果数据变得更加复杂并且构造/流式传输变得昂贵,则必须提供专门的重载并逐字符解析char来跳过它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章