gpt4 book ai didi

c++ - cin.get() 未按预期运行

转载 作者:行者123 更新时间:2023-11-28 03:31:28 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Program not waiting for 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

为什么会这样?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com