C++ 如何在获得下一个字符后正确刷新输入缓冲区,而不必按enter键两次!C++;

C++ 如何在获得下一个字符后正确刷新输入缓冲区,而不必按enter键两次!C++;,c++,cin,C++,Cin,考虑以下代码: #include <iostream> using namespace std; int main() { char input; while (1) { cout << "Enter: "; cin.get(input); cin.ignore(100, '\n'); //requires another `enter` } return 0; } #包括 使用名称空间

考虑以下代码:

#include <iostream>

using namespace std;

int main()
{
    char input;
    while (1) {
        cout << "Enter: ";
        cin.get(input);
        cin.ignore(100, '\n'); //requires another `enter`
    }
    return 0;
}
#包括
使用名称空间std;
int main()
{
字符输入;
而(1){
不能包含
使用名称空间std;
int main()
{
字符输入;
而(1)
{
cout
std::cin.ignore()
将阻止,直到它读取
count
字符或看到其
分隔符为止。在调用输入函数之前,没有可靠的方法来检查
std::cin
是否将阻止。在
input='\n'
调用
ignore()之前检查该条件是防止其阻止的唯一可靠方法

#包括
#包括
int main()
{
字符输入;
while(true){

std::cout这种情况下的一种解决方法可能是使用
std::string
std::getline

#include <iostream>
#include <string>

int main()
{
    while(true)
    {
        std::cout << "Enter: " << std::flush;
        std::string input;

        if(std::getline(std::cin, input) && !input.empty())
        {
            input.front(); // this is your character
        }
    }

    return 0;
}
#包括
#包括
int main()
{
while(true)
{

std::cout如果(input=='\n')继续,为什么不做;而不是忽略?您不能“清除”输入缓冲区,您必须以某种方式使用字符。@Pierre:这是错误的。请参阅。@GabrieldeGrimouard,因为即使它工作,它仍然是一些不必要的编码,而且不是很有效。如果可能的话,我想要一种更好的方法。在这里不可复制。它的工作方式正如您所愿:只按enter键一次。顺便问一下,您使用的是什么操作系统?slig缺点是它不必要地分配内存,但缺点是代码简单。
#include <iostream>
#include <limits>

int main()
{
    char input;
    while (true) {
        std::cout << "Enter: ";
        std::cin.get(input);
        if (input != '\n') {
            // Note: using std::numeric_limits<std::streamsize>::max()
            // disables std::istream::ignore's count check entirely
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
}
#include <iostream>
#include <string>

int main()
{
    while(true)
    {
        std::cout << "Enter: " << std::flush;
        std::string input;

        if(std::getline(std::cin, input) && !input.empty())
        {
            input.front(); // this is your character
        }
    }

    return 0;
}