首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >定制istream机械手

定制istream机械手
EN

Stack Overflow用户
提问于 2016-08-16 18:48:04
回答 1查看 979关注 0票数 2

我想要做一个自定义的istream机械手,它从输入中读取2个字符,然后从输入中跳过2个字符,然后这样做,直到它用完任何输入为止。

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

代码语言:javascript
复制
std::string str;
std::cin >> skipchar >> str;

如果skipchar是我的操作器,如果用户输入1122334455str应该包含113355

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

代码语言:javascript
复制
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;
}

任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-16 19:45:34

这是个很好的问题。我不知道这是否可能。但是,我实现了一些不同的东西,通过使用一个名为>> operator的新类重载Skip2,从而提供了您想要的相同的简短语法。下面是代码(我非常喜欢编写它!:-)

代码语言:javascript
复制
#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;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38982370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档