cin.get() 无法按预期运行

cin.get() not functioning as desired

本文关键字:运行 get cin      更新时间:2023-10-16

可能的重复:
程序不等待 cin

我写了以下代码:

#include <iostream>
using namespace std;
void search(int pre, int a, int b, int x) {
char c;
cout << "Is the number " << ((x == 2) ? b : a) << endl;
c = cin.get(); ////// this does not block
if (c == 'y') return;
else {
cout << "Is the number " << ((x == 2) ? b : a) << " closer to your number than " << pre;
c = cin.get();
if (c == 'y') {
search(a, a, (a + b) / 2, 2);
} //c=='y'
else search(a, (a + b) / 2, b, 1);
}
}
int main() {
int N;
cout << "Enter N? ";
cin >> N;
search(N, 1, N, 1);
return 0;
}

如果您不理解逻辑,则无需担心,因为我的问题与此无关。

在搜索函数中,有两个cin.get(),我需要用户输入一个字符。我的问题是程序仅在第二个 cin.get() 之后阻止输入。

例如:

Is the number 7  //program doesn't wait after this
Is the number 7 closer to your number than 8  //program blocks here for an input

为什么这样做?

你的代码中至少有两个问题。 首先是你是 输入N后将字符留在缓冲区中。 最简单的 解决方案是仅添加对std::cin.ignore( INT_MAX, 'n' );的调用std::cin >> N;后 ;更好的解决方案(因为它允许更多 错误检查)将使用std::getline来读取完整的 行,然后使用std::istringstream解析它。

第二个问题是你分配的结果std::cin.get()char.std::cin.get()返回一个int, 这可能是EOF. 而且你真的想检查它是否EOF在将int转换为char之前:您无法在之后检查,因为 要么一些法律char将比较等于EOF(普通char是 签名),否则char将永远无法等于EOF(普通char是无符号的)。 另一种选择是执行以下操作:

if ( !std::cin.get( c ) ) {
//  EOF or error seen...
}

每次你想读一个char. (这可能在你的 案例,因为如果您确实阅读了EOF,则所有进一步的调用std::cin.get()将返回EOF