1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
|
#include <iostream>
#include <string>
using namespace std;
int get_int(const char * prompt, const char * error, int min=INT_MIN, int max=INT_MAX);
int main()
{
int salescode, bikeprice, modelcode, quantity;
string date;
char answer; //either yes or no
salescode=get_int("Please enter your identification code: ",
"THIS I.D. CODE IS NOT VALID. TRY AGAIN",1,20);
bikeprice=get_int("Please enter the bike price (one unit = 1 Euro): ",
"INVALID PRICE. Bike prices cannot be 0 or more than 500. TRY AGAIN",1,500);
modelcode=get_int("Please enter the 3 digit model code: ",
"INVALID MODEL CODE. TRY AGAIN",0,999);
quantity=get_int("Please enter the quantity sold: ",
"INVALID QUANTITY. TRY A NUMBER FROM 1-10",1,10);
while (true)
{
cout << "Please enter the date in this format dd/mm/yyyy: ";
cin >> date;
cout << "Is this the correct date ?\t" << date << "\t(press y/n): ";
cin >> answer; //gets answer from user
if (answer=='y') {cout << "Thank You!" << endl; break;}
}
return 0;
}
int get_int(const char * prompt, const char * error, int min, int max)
{
int integer;
while (true)
{
cout << prompt;
cin >> integer;
//if the user enters non-numeric input cin.good() returns 0, so !cin.good() evaluates to true
//cin.get()!='\n' checks if the user enters "more" info than he is asked to...
if (!cin.good() || cin.get()!='\n')
{
//clear cin so it can be used for input again
cin.clear();
//ignore every character until the end of line (including the newline character)
while(cin.get()!='\n');
cout << "please don't enter crap..." << endl;
continue;
}
if (integer<min || integer>max)
{
cout << error << endl;
continue;
}
break;
}
return integer;
}
|