【发布时间】:2014-05-01 15:15:24
【问题描述】:
在案例存款部分,我编写了一个循环来验证用户输入是否为整数,但在输入整数以外的内容时,它会将其分配给变量 credit 并重复显示“请输入大于 1 英镑的金额”我试图在显示消息时清除输入,以便可以重复该过程,但我似乎无法清除错误输入的变量。
#include <iostream>
#include <string>
using namespace std;
enum Menusystem // enum is a function used to convert the list of words below into numbers.
{
ShowMenu, EnterName, Account, Deposit, Withdraw, Balance, Exit
} menu;
int main()
{
string customer; // declaring variables and their data types for the menu options.
string accounttype;
string name;
int credit;
int debit;
int currentbal;
bool exit = false; // declaring variable as boolean setting it to false so that when the loop gets to false it will break the loop and exit the program.
int option = 0; // declares showmenu as a integer and sets value to 0 so that the menu will be displayed upon opening the program as in the code below the menu is displayed if option is equal to 0.
while (!exit) // initiates a while loop so that when the loop gets to false it will break the loop and exit the program.
{
switch (menu) // initiates a switch statement which will allow the program to cycle through menu options depending on the menu option the user selects.
{
case ShowMenu:
cout << "[0] - Show menu\n" // displays menu options to user.
<< "[1] - Enter Full Name\n"
<< "[2] - Enter Account Type\n"
<< "[3] - Deposit Funds\n"
<< "[4] - Withdraw Funds\n"
<< "[5] - Display Balance\n"
<< "[6] - Exit Program\n";
cin >> option;
if (option == 0) menu = ShowMenu;
else if (option == 1) menu = EnterName;
else if (option == 2) menu = Account;
else if (option == 3) menu = Deposit;
else if (option == 4) menu = Withdraw;
else if (option == 5) menu = Balance;
else if (option == 6) menu = Exit;
else menu = ShowMenu; // default case is to show the menu.
break;
case EnterName:
system("CLS");
cout << "Please enter your full name >\n";
cin >> customer;
system("CLS");
menu = ShowMenu;
break;
case Account:
menu = ShowMenu;
break;
case Deposit:
system("CLS");
cout << "Please enter an amount you wish to deposit >\n";
cin >> credit;
while (!(cin >> credit)) cout << "Please enter an amount greater than £1";
{
cin.clear();
cin.ignore(100, '\n');
}
system("CLS");
menu = ShowMenu;
break;
case Withdraw:
system("CLS");
cout << "Please enter an amount you wish to withdraw >\n";
cin >> debit;
system("CLS");
menu = ShowMenu;
break;
case Balance:
cout << credit;
cout << customer;
break;
case Exit:
break;
default:
break;
}
}
return 0;
【问题讨论】:
-
您可能想读入字符串并尝试将它们解析为整数,而不是允许使用任何他们想要的 CIN。这是以前的回答
-
您的 cin.clear() 语句实际上不在 while 循环中。
标签: c++ validation loops while-loop