Skipping expected characters like scanf() with cin

前端 未结 5 835
南笙
南笙 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:43

    You can skip the #, or any single character, by using std::istream::ignore

    std::istringstream sstr("1024 # 768");
    
    int main()
    {
       int a, b;
       sstr >> a; 
       sstr.ignore(256,'#');   // ignore until hash character
       sstr >> b;
       std::cout << "a: " << a << " b: " << b << std::endl;
    }
    

提交回复
热议问题