我是第一次从 PHP 使用 C++。我在玩一些代码。根据我的理解,cin.get();
应该在我按下一个键之前阻止窗口关闭,但是它似乎没有工作,因为它之前的代码,我不知道知道问题出在哪里。这是我的代码:
#include <iostream>
#include <cstdlib>
using namespace std;
int multiply (int x, int y);
int main ()
{
int x;
int y;
cout << "Please enter two integers: ";
cin >> x >> y;
int total = multiply(x, y);
cout << total;
cin.get();
}
int multiply (int x, int y) {
return x*y;
}
最佳答案
放一个
cin.ignore(numeric_limits<streamsize>::max(),'\n')
在 >> x >> y;
之后(或在 cin.get()
之前)。
这会刷新 cin
的缓冲区并删除仍然存在的挂起的 \n
,因为您 cin
读取 x 和 y 但也读取最后一次返回(在 y 之后)。这会在您调用 cin.get()
时读入。如果您刷新缓冲区,cin.get()
将看到一个空缓冲区,一切正常。
关于c++ - cin.get() 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8499816/