尽管我尝试使用cin.get()停止它,Visual Studio命令提示符仍然关闭

时间:2014-10-04 08:28:00

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

我的以下基本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;
}

2 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:0)

这可能是发生的事情:

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