How do I flush the cin buffer?

前端 未结 13 1058
無奈伤痛
無奈伤痛 2020-11-22 00:14

How do I clear the cin buffer in C++?

13条回答
  •  不思量自难忘°
    2020-11-22 00:15

    I have found two solutions to this.

    The first, and simplest, is to use std::getline() for example:

    std::getline(std::cin, yourString);
    

    ... that will discard the input stream when it gets to a new-line. Read more about this function here.

    Another option that directly discards the stream is this...

    #include 
    // Possibly some other code here
    cin.clear();
    cin.ignore(numeric_limits::max(), '\n');
    

    Good luck!

提交回复
热议问题