c++ - 跳过输入流值

标签 c++ istream

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

我知道我可以使用 ignore 如果我知道要跳过多少个字符或需要什么分隔符。但是在 IMO 中,当 operator>> 通常只读取下一个空白而不提供任何额外参数时,使用 ignore 是很丑陋的。我也可以使用假人,但这只会让事情变得更糟。

例子

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';
}

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

关于c++ - 跳过输入流值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22015757/

相关文章:

c++ - EnumDesktopWindows (C++) 大约需要 30 分钟才能在 Windows 10 上找到所需的打开窗口

c++在类头中用ostream声明一个函数

c++ - 如何以允许传递临时对象的方式将 std::istream 传递给函数?

c++ - 是否可以防止 CGDB 在退出时清除屏幕?

c++ - 在 C++ 中生成 N 位数字中的所有 R 位数字(组合、迭代)?

c++ - 如何在C++中实现istream&重载?

c++ - 使用 C++ 将 txt 转换为 html

c++ - 为什么 std::getline() 在格式化提取后跳过输入?

android - 如何创建 *.so 文件以动态链接 OpenCV for Android?

c++ - 静态多态的Strategy和CRTP有什么区别?