我想創建一個程序,當用戶輸入一些我沒有定義的內容時,程序會再次提示他。如果用戶輸入無效循環
我用if語句做了它,但它只循環1次,不再做。我嘗試了循環,但每當輸入爲false時,它就會打破條件並拒絕所有輸入。在C++中。
任何幫助,非常感謝。
#include <iostream>
#include <string>
using namespace std;
void xD(){string x;
do{cout << "Retry\n";
cin >> x;}while(true);}
//declaring a function to make the shop
void shop(){
string x;
float coins = 500;
float bow_cost = 200;
cout << "welcome to the shop\n";
cout << "Bow(bow)costs 150 coins.\n";
cin >> x;
// if u chose bow you get this and get to choose again
if (x == "bow"){
cout << "you bought the bow.\n you now have " <<coins - bow_cost << " coins." << endl; cin >> x;}
/*now the problem that whenever I excute the code and type something other than bow it gives me the cin only once more and then fails even if I type bow in the 2nd attempt*/
//in my desperate 5k attempt, I tried creating a function for it.. no use.
//i want it o keep prompting me for input till i type "bow" and the other block excutes. but it never happens.
else{xD();}
}
int main(){
string name;
string i;
cout << "if you wish to visit the shop type \"shop\"\n";
cin >> i;
if(i == "shop"){shop();}
else{cin >> i;}
return 0;
}
非常感謝你,它像一個魅力工作! –
現在每當我輸入一個無效值然後輸入一個有效的值時,程序意外結束。 –