[英]Skip some code after entering a value and exit the program
我正在創建一個簡單的代碼以取整數值10次。 如果用戶在任何時候輸入值“ 5”,系統應打印一條消息,“您輸入了5,您輸了”。 這是代碼
int main()
{
int num = 0;
int i;
for (i = 1; i<= 10; i++)
{
cout << "Enter a number other than 5\n";
cin >> num;
if (num == 5)
{
cout << "Hey, you entered 5. You lose!\n";
break;
}
}
cout << "You win!";
return 0;
}
現在我不知道的是,在用戶輸入5后如何關閉程序。我對編碼非常陌生,如果這個問題聽起來很愚蠢,我真的很抱歉。 另外,如果您能以最簡單的方式進行解釋,那對您也很友好。 謝謝
您可以這樣做:
for (i = 1; i<= 10; i++)
{
cout << "Enter a number other than 5\n";
cin >> num;
if (num == 5)
{
cout << "Hey, you entered 5. You lose!\n";
return 0; // This will end function main and return 0. Thus your program will end.
}
}
還有更多閱讀。
break
方式只會停止for循環。 但是:
cout << "You win!";
仍會被打印。 如果使用return,則不會再執行main
語句。 因為return
將終止在其中調用它的函數,在這種情況下為main
。
現在我不知道的是,用戶輸入5后如何關閉程序。
更換
break;
與
exit(0);
要么
return 0;
break
只會從循環中退出,並且您正在打印cout << "You win!";
無條件的。
上面提到的其他兩種方法無疑是最好的。 但是,即使在用戶輸入5之后,如果您還有一些未完成的業務要處理,您可以使用臨時變量(例如temp)來幫助您。
int main()
{
int num = 0,tmp=0;
int i;
for (i = 1; i<= 10; i++) {
cout << "Enter a number other than 5\n";
cin >> num;
if (num == 5) {
tmp=1;
cout << "Hey, you entered 5. You lose!\n";
break;
}
//unfinished work
}
//unfinished work
if(tmp==0)
cout << "You win!";
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.