【问题标题】:Visual Studio command prompt closes despite that I tried to stop it with cin.get()尽管我尝试使用 cin.get() 停止 Visual Studio 命令提示符,但它仍会关闭
【发布时间】:2014-10-04 08:28:00
【问题描述】:

我的以下基本 C++ 代码不起作用。当我在 Visual Studio express 中运行它时,它只是在我输入第二个数字后关闭命令提示符。提前致谢。

#include <iostream>

using namespace std;

int main()
{

    int num1, num2, answer;

    cout << " Enter a number: ";
    cin >> num1;
    answer = num1 * num1;
    cout << " the sum of the number is: " << answer << endl;

    cout << "Enter a 2nd number";
    cin >> num2;
    answer = answer + num2;
    cout << "The sum of the two numbers is: " << answer << endl;

    cin.get();
    return 0;
}

【问题讨论】:

  • 尝试在第一个输入之后也放一个 cin.get()。

标签: c++ visual-c++ visual-studio-2012


【解决方案1】:

问题是输入缓冲区中还有字符。

无论如何,您不应该添加“棘手”命令来保持控制台打开(您必须记住将它们从“生产”代码中删除)。

您可以运行您的程序无需调试器模式 (CTRL + F5),Visual Studio 将保持控制台应用程序窗口打开,直到您按下一个按钮(只需检查Project -&gt; Properties -&gt; Linker -&gt; System -&gt; Sub System -&gt; Console (/SUBSYSTEM:CONSOLE) 中的设置)。

当然,如果您正在调试 (F5),在return 0; 上设置断点是最好的选择。

【讨论】:

    【解决方案2】:

    这可能是正在发生的事情:

    Last cin.get() 读取您在输入第二个数字后按下的 Enter 键。您还需要一个cin.get(),以便命令提示符等待您按下另一个键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-10
      • 2014-04-10
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      相关资源
      最近更新 更多