cin.get() 无法按预期运行
cin.get() not functioning as desired
可能的重复:
程序不等待 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
。
相关文章:
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 代码在main()中运行,但在函数中出现错误
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- Cpp-Tuple使用带有变量的get
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何在运行中期切换GTK CSS style_context
- 如何在MS Visual Studio 2019中运行QT UI
- 如何通过cpp程序运行shell脚本
- IPC使用多个管道和分支进程来运行Python程序
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- cin.get() 无法按预期运行
- 使用Qt(QProcess)运行apt-get
- 在后台运行的进程Get失败