如何在c ++应用程序中清除输入缓冲区?

Iow*_*a15 0 c++ input

我制作了很多简单的控制台c ++应用程序,我面临的一个问题是输入缓冲区.我尝试过cin.ignore和flush(),但它们似乎并不适合我.

如果我有以下代码:

cin >> char1;
cin >> char2; 
Run Code Online (Sandbox Code Playgroud)

我按下:1(空格)2(回车),只有一个输入,1存储到char1,2存储到char2.

对不起,如果我对我的要求有点模糊.如果人们不理解,我会尝试编辑这个问题.

Mat*_*Mat 5

您可以使用getline一次读取整行,然后使用std :: string at,如果需要第一个char,或者isstringstream如果需要第一个数字则使用.

char char1;
std::string input;

getline(std::cin, input);
if (!std::cin.good()) {
  // could not read a line from stdin, handle this condition
}

std::istringstream is(input);
is >> char1;
if (!is.good()) {
  // input was empty or started with whitespace, handle that
}
Run Code Online (Sandbox Code Playgroud)

如果经常这样做,请将其包裹在函数中.通过上述,如果你打直接输入(字符输入的),或者如果输入开始空白数据,is!good()这样char1不会被置位.

或者,在您检查完毕后cin,您可以简单地:

if (input.empty()) {
  // empty line entered, deal with this
}
char1 = input.at(0);
Run Code Online (Sandbox Code Playgroud)

有了它,如果字符串是非空的,char1将被设置为第一个charif input,无论是什么(包括空格).

注意:

is >> char1;
Run Code Online (Sandbox Code Playgroud)

只读取第一个字符,而不是第一个数字(与input.at()版本相同).因此,如果输入是123 qze,char1将接收'1'(如果是ASCII,则为0x31),而不是值123.不确定这是否是您想要的.如果它不是您想要的,请读取int变量,然后正确投射.