簡體   English   中英

如果用戶遇到問題,如何停止程序?

[英]How do I stop a program if the user gets something wrong?

我正在寫一個程序,讓用戶輸入自己有多少錢,如果少於50,它會說“

Sorry not Enough

我希望程序到此結束。

這是我編寫的代碼:

cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
}
cout << "Here are the items you can buy" << endl;
int a = 50;
int b = 200;

當然,這不是我編寫的全部代碼。 如果該人寫的數字少於50,該如何停止代碼?

謝謝!

您必須在以下內容后寫return

cout << "Sorry not enough" << endl; 

這將停止代碼。

當您從main() return時,程序將結束,因此您應該安排發生這種情況。

另外,您可以調用exit() ,但這是一個壞主意,因為析構函數將不會運行。

您可以這樣編寫代碼:

cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
}
else {
   cout << "Here are the items you can buy" << endl;
   // Operations you want to perform 
}

在C ++中使用return語句或exit()函數將退出程序。 您的代碼如下所示:

int main()
{
cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
    return 0;
}
cout << "Here are the items you can buy" << endl;
int a = 50;
int b = 200;
}

相反,使用exit()函數,它看起來像:

#include<stdlib.h> //For exit function
int main()
{
cin >> money;
if (money <= 50) {
    cout << "Sorry not enough" << endl;
    exit(0);
}
cout << "Here are the items you can buy" << endl;
int a = 50;
int b = 200;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM