Skipping expected characters like scanf() with cin

前端 未结 5 834
南笙
南笙 2020-12-03 19:12

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

5条回答
  •  情话喂你
    2020-12-03 19:56

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

    #include 
    #include 
    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;
    }
    

提交回复
热议问题