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

标签 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;
}

最佳答案

使用 cin.get(),您只能获得这些字符中的一个,被视为 char。 您将看不到输出,因为命令提示符将在程序完成后立即关闭。放置 cin.get() 会强制程序在关闭之前等待用户输入 key ,您现在可以看到程序的输出。

 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;

关于c++ - 什么类型的情况会导致 cin.get() 函数不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24709168/

相关文章:

c++ - 为什么某些 C/C++ 函数使用指针作为参数?

c++ - 不一致的警告 "conversion from ' const unsigned char' to 'const float' requires a narrowing conversion”

c++ - 默认参数值错误 [Visual C++ 2008 中的错误?]

c++ - Qt3D: "Mesh is empty, nothing to load"消息

c++ - 使用静态函数初始化 static const int

c# - 如何将 C# 和 C++ 程序集链接到单个可执行文件中?

windows - Windows 10 上的 Visual Studio 2010 x64 编译器

c++ - MSVC : Why are functions containing basic QString operations not inlined?

C++:复制构造函数崩溃

c++ - 对象的排序 vector