什么类型的情况导致cin.get()函数不起作用?

use*_*526 0 c++ visual-c++

我对c ++很新,我想知道为什么我的cin.get()没有停止cmd中的程序在完成时立即关闭?我在我之前的代码上尝试了cin.get()并且它工作正常,但由于某种原因它不适用于此代码.

#include <iostream>

int main()
{
       using namespace std;
       int carrots;
       cout << "How many carrots do you have?" << endl;
       cin >> carrots;
       cout << "You have " << carrots << endl;
       cin.get();
       return 0;
}
Run Code Online (Sandbox Code Playgroud)

bum*_*paw 5

使用时cin.get(),您只能获得其中一个字符,视为char.您将无法看到输出,因为命令提示将在程序完成后立即关闭.把cin.get()部队的程序等待用户输入密钥之前将关闭,你现在可以看到你的程序的输出.

 using namespace std;
       int carrots;
       cout << "How many carrots do you have?" << endl;
       cin >> carrots;
       cout << "You have " << carrots << endl;
       cin.get();
       cin.get();// add another one
       return 0;
Run Code Online (Sandbox Code Playgroud)


小智 5

你必须添加

cin.ignore();
Run Code Online (Sandbox Code Playgroud)

之前

cin.get();
Run Code Online (Sandbox Code Playgroud)

清除先前返回的输入缓冲区!

完整代码

#include <iostream>

int main()
{
    using namespace std;
    int carrots;
    cout << "How many carrots do you have?" << endl;
    cin >> carrots;
    cout << "You have " << carrots << endl;
    cin.ignore();
    cin.get();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)