Hello SweatyCoder,
"bool" is a variable type like "chsr", "short", "int" and "double". The difference is that a "bool" is only 1 byte to hold a (0) zero meaning "false" or a (1) meaning "true". This is a vary handy variable type that you will be using more in the future.
"break" is a key work and as the name implies it is used to break out of something. Generally used with for loops, do.while loops, while loops and the switch. The switch you will get to in the future.
The "cin.clear()" is a function of "cin", maybe not the most accurate, but will work for now, and is used to clear the state bits on the stream.
http://www.cplusplus.com/reference/ios/ios/clear/
The idea of "cin.ignore(...)" is to clear the input buffer of whatever may be left there. There are several ways to write this: As
salem c has used this would be considered the most portable way that any compiler can use. Another way, most often seen, is
cin.ignore(1000, '\n');
. The first parameter is just a large number. The second parameter, the "\n", is what the ignore would clear to. That is the "ignore" will clear from the input 1000 characters or to the "\n" whichever comes first.
The combination of ".clear()" and ".ignore(...)" is usually used after formatted input. An example
cin >> num;
where "num" is defined as an int although it could be any numeric type. As formatted input the "cin" expects a numeric value to be typed in. If not "cin" will fail and be unusable the rest of the program unless you use "cin.clear();".
The down side to formatted input is that it will leave the "\n" in the input buffer which could cause a problem especially if you use "std::getline()" for unformatted input. The "getline" will extract up to and including the "\n", but discards the "\n" leaving the input buffer empty.
This is untested. I will work on that part shortly and post any changes I may need to make.
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
|
do
{
cout << "Month: ";
cin >> birthMonth;
if (birthMonth < 1 || birthMonth > 12)
std::cout << "\n Invalid Month! Try again.\n";
} while (birthMonth < 1 || birthMonth > 12);
do
{
cout << "Day: ";
cin >> birthDay;
if (birthDay < 1 || birthDay > 31)
std::cout << "\n Invalid Day! Try again.\n";
} while (birthDay < 1 || birthDay > 31);
do
{
cout << "Year: ";
cin >> birthYear;
if (birthYear < 1900 || birthYear > 2020)
cout << "\n Invalid Year! Try again!\n";
} while (birthYear < 1900 || birthYear > 2020);
|
This will keep each section in in the loop until you enter valid information. Not as fancy as what
salem c posted, but I hope it will help you understand what he did.
Andy