我已經創建了一些C++代碼,應該檢查用戶的輸入是否正確,但它不是我想要的。無論何時你首先鍵入一個整數,然後輸入一個整數,終端垃圾郵件你想再次嘗試y/n幾次。我試圖限制它可以輸出的次數,但沒有任何工作。功能來檢查用戶的輸入是否正確無效
#include <iostream>
#include <limits>
using namespace std;
int again()
{
char yorn = 'q';
cout << "\n Would you like to run this program again? y/n: ";
cin >> yorn;
if (cin.fail()) {
int dof1 = 1; // dof1 stands for don't overflow 1
for (int i = 0; i < dof1; i++) {
cout << "ERROR -- You did not enter a valid symbol";
// get rid of failure state
cin.clear();
// discard 'bad' character(s)
cin.ignore(numeric_limits<streamsize>::max(), '\n');
bool check = again();
if (check == true) {
check = false;
return again();
}
else
return 0;
}
}
switch (yorn) {
case 'y':
return true;
break;
case 'n':
return false;
break;
default:
return again();
break;
}
}
int main()
{
int choice = 0;
cout << "\nWelcome to the Weight Tracker! Type 000 at any time to exit\n"
<< "Choose the option you would like to use below \n"
<< "1) \n"
<< "2) \n"
<< "3) \n"
<< "Option selected: ";
cin >> choice;
if (cin.fail()) {
int dof2 = 1; // dof2 stands for don't overflow 2
for (int i = 0; i < dof2; i++) {
cout << "ERROR -- You did not enter an integer";
// get rid of failure state
cin.clear();
// discard 'bad' character(s)
cin.ignore(numeric_limits<streamsize>::max(), '\n');
bool check = again();
if (check == true) {
check = false;
return main();
}
else
return 0;
}
}
switch (choice) {
case 1:
cout << " use later";
break;
case 2:
cout << " use later";
break;
case 3:
cout << " use later";
break;
default:
cout << "ERROR -- Input invalid \n";
bool check = again();
if (check == true) {
check = false;
return main();
}
else
return 0;
break;
}
return 0;
}
以遞歸方式調用main?你確定你想這樣做嗎?它會工作,但絕對不是好的做法。 – elanius