How do I flush the cin buffer?

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

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

13条回答
  •  清歌不尽
    2020-11-22 00:28

    cin.clear();
    fflush(stdin);
    

    This was the only thing that worked for me when reading from console. In every other case it would either read indefinitely due to lack of \n, or something would remain in the buffer.

    EDIT: I found out that the previous solution made things worse. THIS one however, works:

    cin.getline(temp, STRLEN);
    if (cin.fail()) {
        cin.clear();
        cin.ignore(numeric_limits::max(), '\n');
    }
    

提交回复
热议问题