Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skipping expected characters like scanf() with cin

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

like image 778
eldos Avatar asked Feb 13 '14 20:02

eldos


2 Answers

You can skip the # by extracting it into a character:

std::istringstream iss("10 # 20");

int main()
{
   int a, b; char hash;
   iss >> a >> hash >> b;

   assert(a == 10 && b == 20);
}
like image 62
David G Avatar answered Sep 27 '22 23:09

David G


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;
}
like image 42
Don Reba Avatar answered Sep 27 '22 21:09

Don Reba