Michael Naifield Michael Naifield - 1 year ago 95
C++ Question

Making a custom istream manipulator

I want to make a custom

manipulator that reads 2 characters from the input, then skips 2 characters from the input, and does that until it runs out of any input.

For example, if I have code like this:

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

is my manipulator, if the user enters
should contain

This is what I've got so far, I don't know what I should put in the while loop condition to make this code work properly:

istream& skipchar(istream& stream)
char c;

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

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

return stream;

Any help would be appreciated.

Answer Source

That's a very nice question. I don't know if it's possible. But I implemented something different which gives you the same short syntax you wanted, by overloading the >> operator with a new class called Skip2. Here is the code (which I really enjoyed writing! :-) )

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

using namespace std;

class Skip2 {
    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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download