【问题标题】:Why is the Console Closing after I've included cin.get()?为什么在我包含 cin.get() 后控制台关闭?
【发布时间】:2011-06-18 19:01:03
【问题描述】:

我刚刚开始使用 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;
}

【问题讨论】:

    标签: c++ visual-studio-2010


    【解决方案1】:
    cin >> carrots;
    

    这一行在输入流中留下一个尾随的换行符,然后被下一个cin.get() 使用。在此之前直接做一个简单的cin.ignore()

    cin.ignore();
    cin.get();
    

    【讨论】:

    • 解释得很好。
    【解决方案2】:

    因为cin &gt;&gt; carrots 不会读取你输入整数后输入的换行符,而cin.get() 会读取输入流中留下的换行符,然后程序结束。这就是控制台关闭的原因。

    【讨论】:

      【解决方案3】:
      cin >> carrots;
      

      读取int,但留下换行符。

      cin.get();
      

      读取该换行符,程序结束。

      【讨论】:

        【解决方案4】:
        cin >> carrots;
        

        获取一个整数输入,按回车键后换行。

        cin.ignore();
        

        在获取输入后放置这个以避免控制台退出。

        【讨论】:

          猜你喜欢
          • 2022-11-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-04
          • 2018-09-06
          • 1970-01-01
          • 2018-04-15
          相关资源
          最近更新 更多