【问题标题】:How can I terminate the console?如何终止控制台?
【发布时间】:2016-10-04 12:20:36
【问题描述】:

这里是新手。我有以下内容:

#include<iostream>
#include<string>
#include<iomanip>
#include<cmath>
#include<stdlib.h>

using namespace std;

int main() {
    int choice;
    double radius, length, width, base, height;
    const double PI = 3.14159;

    cout << ":Geometry Calculator:\n\n";
    cout << "1. Calculate the Area of a Circle \n";
    cout << "2. Calculate the Area of a Rectangle \n";
    cout << "3. Calculate the Area of a Triangle \n";
    cout << "4. Quit\n";
    cout << "4. Please pick number: " ;
    cin >> choice;

    switch (choice) {
    case 1:
        double aCirc;
        cout << "Enter the RADIUS of your Circle: ";
        cin >> radius;
        aCirc = PI * pow(radius, 2);
        cout << "The AREA of your CIRCLE IS: " << aCirc;
        break;
    case 2:
        double aRec;
        cout << "Enter the LENGTH and WIDTH of your Rectangle (seprate your numbers with a space): ";
        cin >> length >> width;
        aRec = length * width;
        cout << "The AREA of your Rectangle is: " << aRec;
        break;
    case 3:
        double aTri;
        cout << "Enter the BASE and HEIGHT of your Triangle (separate your numbers with a space): ";
        cin >> base >> height;
        aTri = (base * height) / 2;
        break;
    case 4:
        exit();
    default:
        cout << "\n You entered an Invalid Number GoodBye No Number" << endl;
    }


    return 0;
}

我试图在用户按下“4”后立即终止控制台不工作,有人可以帮忙吗?感谢您的时间和专业知识。

【问题讨论】:

  • 你的意思是,当用户按下“4”时程序终止,而不是当用户按下“4”和“返回”时?
  • 是的,没错,很抱歉造成混乱。

标签: c++ math switch-statement terminate


【解决方案1】:

一般来说,调用exit() 是一种不好的做法,因为如果您的应用程序包含较大的代码,它会在您尝试调试并理解为什么您的应用程序突然消失的原因时出现意外行为(假设您不记得所有代码)。

在您的示例中,我认为调用 break 并发出日志语句会更合适。

【讨论】:

    【解决方案2】:

    您可以使用getch() 或conio.h。它将返回一个字符,您可以将其转换为等效数字。 getch() 会阻止程序,直到您按下一个键。正如@PazO 所说,不要使用exit

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多