c++ - 制作自定义 istream 操纵器

标签 c++ io istream manipulators

我想制作一个自定义的 istream 操纵器,它从输入中读取 2 个字符,然后从输入中跳过 2 个字符,直到用完所有输入为止。

例如,如果我有这样的代码:

std::string str;
std::cin >> skipchar >> str;

其中 skipchar 是我的操纵器,如果用户输入 1122334455str 应包含 113355

这是我到目前为止所得到的,我不知道应该在 while 循环条件中放入什么以使该代码正常工作:

istream& skipchar(istream& stream)
{
    char c;

    while(1)
    {
        for (int i = 0; i < 2; ++i)
            stream >> c;

        for (int i = 0; i < 2; ++i)
            stream.ignore(1, '\0');
    }

    return stream;
}

如有任何帮助,我们将不胜感激。

最佳答案

这是一个非常好的问题。我不知道是否可能。但我实现了一些不同的东西,通过使用名为 Skip2 的新类重载 >> 运算符,为您提供了所需的相同短语法。这是代码(我真的很喜欢写!:-))

#include <iostream>
#include <string>
#include <istream>
#include <sstream>

using namespace std;

class Skip2 {
public:
    string s;
};

istream &operator>>(istream &s, Skip2 &sk) 
{
    string str;
    s >> str;

    // build new string
    ostringstream build;
    int count = 0;
    for (char ch : str) {
        // a count "trick" to make skip every other 2 chars concise
        if (count < 2) build << ch;
        count = (count + 1) % 4;
    }

    // assign the built string to the var of the >> operator
    sk.s = build.str();

    // and of course, return this istream
    return s;
}



int main()
{
    istringstream s("1122334455");
    Skip2 skip;

    s >> skip;
    cout << skip.s << endl;

    return 0;
}

关于c++ - 制作自定义 istream 操纵器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38982370/

相关文章:

c++ - 学习C++解析

c - 我想将 stdin 解释为二进制文件。为什么 freopen 在 Windows 上失败?

c++ - 确定外部文件中字符串的长度

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

c++ - C 共享对象,带有 C++ 存档、静态 Ctors/Dtors 和 dlopen

c++ - igraph 中的直接选择器

C++ 和 CTime & 系统时钟更改

java - 客户端/服务器程序 : Connection Reset

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

"cin"和 "File"的 C++ 通用接口(interface)