Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cin analougus of scanf formatted input?

Tags:

c++

std

input

With scanf there's, usually, a direct way to take formatted input:

1) line with a real number higher than 0, and less than 1. Ending on 'x', e.g: 0.32432523x

scanf("0.%[0-9]x", &number);

2) line represents an addition in the format :30+28=fifty-eight

scanf(":%d+%d=%99s", &number1, &number2, &total);

What is the cin solution, using only the standard library?

like image 582
Alessandro Stamatto Avatar asked Jan 15 '13 03:01

Alessandro Stamatto


Video Answer


1 Answers

You can make a simple class to verify input.

struct confirm_input {
    char const *str;

    confirm_input( char const *in ) : str( in ) {}

    friend std::istream &operator >>
        ( std::istream &s, confirm_input const &o ) {

        for ( char const *p = o.str; * p; ++ p ) {
            if ( std::isspace( * p ) ) {
                std::istream::sentry k( s ); // discard whitespace
            } else if ( (c = s.get() ) != * p ) {
                s.setstate( std::ios::failbit ); // stop extracting
            }
        }
        return s;
     }
};

usage:

std::cin >> x >> confirm_input( " = " ) >> y;
like image 57
Potatoswatter Avatar answered Oct 12 '22 13:10

Potatoswatter