我的以下基本 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;
}
最佳答案
问题是输入缓冲区中有剩余字符。
无论如何,您不应该添加“棘手的”命令来保持控制台打开(您必须记住将它们从“生产”代码中删除)。
您可以不使用调试器模式(CTRL + F5)运行您的程序,Visual Studio 将保持控制台应用程序窗口打开,直到您按下一个按钮(只需检查 Project -> Properties -> Linker -> System -> Sub System -> Console (/SUBSYSTEM:CONSOLE)
中的设置)。
当然,如果您正在调试 (F5),return 0;
上的断点是最佳选择。
关于c++ - 尽管我尝试使用 cin.get() 停止它,但 Visual Studio 命令提示符仍关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26191061/