I have a problem where I'm trying to write a program to calculate the compensation for days without luggage on Air Canada. I need to have an error message if the user types in a negative or something other than a number, but I'm using default for compensation that is more than 6 days. How would I put an error check in here while still being able to keep a case or default for any more than 6?
#include <iostream>
using namespace std;
int main() {
int days = 0;
cout << "Enter days you've been without your luggage: ";
cin >> days;
switch(days) {
case 0:
case 1:
cout << "You will be compensated $0." << endl;
break;
case 2:
case 3:
cout << "You will be compensated $200." << endl;
break;
case 4:
case 5:
cout << "You will be compensated $350." << endl;
break;
default:
cout << "You will be compensated $500." << endl;
}
Hint: You can edit your post, highlight your code and press the <> formatting button.
You can use the preview button at the bottom to see how it looks.
I found the second link to be the most help.
You could do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
std::cout << "Enter days you've been without your luggage: ";
std::cin >> days;
while (!std::cin || days < 0)
{
if (!std::cin)
{
std::cout << "\n Invalid entry! Must be a number\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires header file <limits>.
}
elseif (days < 0)
std::cout << "\n Invalid entry! Needs to be a positive number\n";
std::cout << "Enter days you've been without your luggage: ";
std::cin >> days;
}
The "!std::cin" will catch anything that is not a number because of the formatted input. This way you can validate you entry in two ways giving a number that the "switch" can use.