为什么在我包含 cin.get() 后控制台关闭?
Why is the Console Closing after I've included cin.get()?
我刚刚开始使用C++Primer Plus学习C++,但其中一个示例出现了问题。就像我指导的书一样,我在最后包含了cin.get()
,以防止控制台自行关闭。然而,在这个例子中,它仍然会自己关闭,除非我添加两个我不理解的cin.get()
语句。我正在使用Visual Studio Express 2010。
#include <iostream>
int main()
{
int carrots;
using namespace std;
cout << "How many carrots do you have?" << endl;
cin >> carrots;
carrots = carrots + 2;
cout << "Here are two more. Now you have " << carrots << " carrots.";
cin.get();
return 0;
}
cin >> carrots;
这一行在输入流中留下一个尾随的换行符,然后由下一个cin.get()
使用。在那之前直接做一个简单的cin.ignore()
:
cin.ignore();
cin.get();
因为cin >> carrots
不读取您在键入整数后输入的换行符,而cin.get()
读取输入流中剩下的换行符然后程序结束。这就是控制台关闭的原因。
cin >> carrots;
读取CCD_ 7,但留下一个换行符。
cin.get();
读取换行符,程序结束。
cin >> carrots;
获取一个整数输入,并在按enter键后留下一行新行。
cin.ignore();
将其放置在获得输入之后,以避免控制台退出。
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 编译包含字符串的代码时遇到问题
- c++库的公共头文件中应该包含什么
- C++:将控制台输出存储在宏中更好吗
- 将包含C样式数组的对象初始化为成员变量(C++)
- 是否需要删除包含对象的"pair"?
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 使用mongocxx驱动程序时包含头文件问题
- 如何在h文件中包含.o对象文件
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- C++附加控制台包含错误
- visual 无法在控制台应用程序项目中包含头文件C++
- 拥有一个包含MFC项目和用于单元测试的控制台应用程序的解决方案
- 制作一个c++控制台应用测试.控制台不接受包含引号的输入
- 在控制台应用程序中包含"help"消息的最佳方法是什么?
- 为什么在我包含 cin.get() 后控制台关闭?
- 编译器构造-在编译c++控制台我的程序时,我在包含的矢量头文件中得到错误,这是可能的吗?