[英]How to cout invalid input and then reinput in and if else statement
我是編碼新手,需要幫助
if(x == "D" || x == "d"){
cout << "How many 5c coins? ==> ";
cin >> j;
five += j;
cout << "How many 10c coins? ==> ";
cin >> a;
ten += a;
cout << "How many 20c coins? ==> ";
cin >> q;
twenty += q;
cout << "How many 50c coins? ==> ";
cin >> k;
fifty += k;
我希望用戶輸入一個整數,所以我聲明了 int = j, a, q, k 如何做到這一點,例如,如果用戶輸入字母 P,它將出現錯誤,用戶可以重新輸入
使用循環允許用戶在用戶輸入無效輸入的情況下重新輸入輸入。
你可以做:
bool validinput = true;
if(x == "D" || x == "d"){
do{
validinput = true;
cout << "How many 5c coins? ==> ";
cin >> j;
if (cin.fail()) {
cout << "Please enter a valid value.." << endl;
cin.clear(); //reset state bits
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //discard all characters from the input buffer, or until a newline is read.
validinput = false;
}
}while(validinput == false);
//repeat same to validate other numeric inputs
您將需要一個循環:
do {
int num;
if(cin >> num)
{ /* input is good */
...
break;
}
else
{ /* error */ }
} while(true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.