Skipping expected characters like scanf() with cin

c++, cin, cstdio, iostream, scanf

Solution

You could create your own stream manipulator. It is fairly easy.

#include <ios>
#include <iostream>
using namespace std;

// skips the number of characters equal to the length of given text
// does not check whether the skipped characters are the same as it
struct skip
{
    const char * text;
    skip(const char * text) : text(text) {}
};

std::istream & operator >> (std::istream & stream, const skip & x)
{
    ios_base::fmtflags f = stream.flags();
    stream >> noskipws;

    char c;
    const char * text = x.text;
    while (stream && *text++)
        stream >> c;

    stream.flags(f);
    return stream;
}

int main()
{
    int a, b;
    cin >> a >> skip(" # ") >> b;
    cout << a << ", " << b << endl;
    return 0;
}

Problem

How to achieve `scanf("%d # %d",&a,&b);`sort of effect with `cin` in C++ ?

Original source