【问题标题】:console program exits [duplicate]控制台程序退出[重复]
【发布时间】:2011-09-07 18:53:13
【问题描述】:

可能重复:
How to stop C++ console application from exiting immediately?

我有以下控制台程序:

#include <iostream>
using namespace std;

int main()
{
    int a;
    int b;


cout<<"Enter a";
cin>>a;

cout<<"Enter b";
cin>>b;

int result = a*b;

cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;
    return 0;
}

一旦我运行程序,它会接受输入但在我查看结果之前退出。我需要做什么才能让程序在我查看结果之前不退出?。

【问题讨论】:

  • 你使用的是什么环境?
  • 您可以随时查看结果。只需捕获输出或从现有控制台或其他东西运行它。

标签: c++


【解决方案1】:

顺便说一句,在获得ab 的输入之前,您已经计算了result 的值,因此如果您的编译器汇编代码,result 的值将要么是0零初始化堆栈上声明的任何变量,或者只是一些随机值。实际上,您甚至不需要声明result ...您可以在cout 语句中计算它的值。所以你可以调整你的最后一行,使它看起来像这样:

cout << "You entered" << a <<"and you entered"<< b 
     << "Their product is" << (a*b) << endl;

要阻止程序退出,您可以从stdin 中获取另一个char。因此,您可以执行以下操作:

cout << "Press any key to exit..." << endl;
char extra;
cin >> extra;

【讨论】:

    【解决方案2】:

    return 0; 语句之前添加system ("pause"); 怎么样?

    【讨论】:

    • 构建问题:'system' 未在此范围内声明
    • #include &lt;cstdlib&gt; 将为您声明system。但最好是了解如何让您的环境在程序退出后保持控制台打开。
    【解决方案3】:

    使用 getche() 、getch() 或任何基于字符的输入函数。

    int main()
    {
        int a;
        int b;
        int result = a*b;
    
    cout<<"Enter a";
    cin>>a;
    
    cout<<"Enter b";
    cin>>b;
    
    cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;
    getch(); //use this.It would wait for  a character to input.
    return 0;
    }
    

    一般我们用回车来退出程序,它的ASCII值是由它获取的。但是因为我们不将它存储在变量中是没有用的。

    【讨论】:

      【解决方案4】:

      您可以要求更多反馈

      cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;
      
      char stop;
      cin >> stop;
      

      【讨论】:

        【解决方案5】:

        当我在 Windows 上时,我喜欢使用 conio.h 中的 getch(),但这不是很便携:/

        【讨论】:

          【解决方案6】:

          Windows:

          //1
              system ("pause");
          //2
              #include<conio.h>
              _getch();
          

          .NET (Windows):

          System::Console::ReadLine();
          

          总体:

              #include <cstdlib.h>
              return EXIT_SUCCESS;
          

          【讨论】:

          • 我不知道&lt;conio.h&gt; 是什么(或者实际上是_getch),但我猜它也只适用于Windows。在标准 C++ 中,您需要 getchar() 来自 &lt;cstdio&gt;cin.get() 来自 &lt;iostream&gt;
          • @Secko:在我的版本中没有。标准函数适用于任何符合标准的编译器。
          • 嗯,看来是这样。但是,它可以在我的带有 gcc 的机器上运行。
          • 此外,在 C++ 中,您应该从 &lt;cstdlib&gt; 获得 EXIT_SUCCESS,而不是已弃用的 C 标头;而且你根本不需要main 末尾的return 语句。
          • @Mike:对,我已经习惯了写 C,所以你去吧,返回只是为了让他知道它的去向。
          猜你喜欢
          • 2011-06-06
          • 1970-01-01
          • 2012-09-13
          • 2015-11-15
          • 2014-09-04
          • 2016-05-25
          • 2014-02-17
          • 1970-01-01
          • 2010-11-10
          相关资源
          最近更新 更多