【问题标题】:C++ console application exiting immediately? [duplicate]C++ 控制台应用程序立即退出? [复制]
【发布时间】:2014-09-04 19:26:02
【问题描述】:

我正在尝试使用 Visual Studio 2013 学习 C++,但我遇到了一个阻止我继续学习的问题。在调试时启动控制台并从用户控制台获取输入后立即关闭。如何让我的程序等待我的命令关闭?

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double number, answer;
    cout << "Enter a number: ";
    cin >> number;
    answer = sqrt(number);
    cout << "Square root is " << answer << endl;
    cin.get();
    return 0;
}

【问题讨论】:

标签: c++ visual-studio console-application


【解决方案1】:

删除声明

cin.get();

并使用 Ctrl+F5 从 IDE 运行程序。

此声明

cin.get();

在上述输入语句中输入数字后,读取标准流的输入缓冲区中存在的换行符。或者在调用 cin.get() 清除缓冲区之前,使用适当的参数调用 cin.ignore(至少作为 cin.ignore())。

【讨论】:

  • 如果以Ctrl-F5开头,是什么阻止了程序退出后控制台窗口关闭?
  • @MarkRansom,无论 VS 使用什么来运行你的程序,它都会在之后暂停它。我从来不知道为什么这种行为只在不调试时才存在。
  • @Mark Ransom MS VS 在关闭窗口之前插入自己的暂停。
  • 但前提是您的项目配置正确:对于普通项目,请参见 this answer,对于 makefile 项目,请参见 this one
  • @osman 然后使用我在帖子中指出的 std::cin.ignore。
【解决方案2】:
How can I make my program wait my command to close?

Ctrl+F5 适合我。

【讨论】:

  • 有了这个答案,你必须确保你的项目配置正确:正常项目见this answer,makefile项目见this one
【解决方案3】:

看起来您缺少忽略语句。前一个 cin 的回车仍在您的缓冲区中。

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double number, answer;
    cout << "Enter a number: ";
    cin >> number;
    answer = sqrt(number);
    cout << "Square root is " << answer << endl;
    cin.ignore(INT_MAX, '\n');
    cin.get();
    return 0;
}

【讨论】:

    猜你喜欢
    • 2012-09-13
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    相关资源
    最近更新 更多