using default for something else but still need an error message - switch statement

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;
}

return 0;
}
read input as a string, and handle bad input outside the switch, and if valid, only then enter the switch.

eg
string days;
cin >> days;
if(myvalidcheck(days)) //all digits and positive perhaps?
{
int days4switch = stoi(days);
switch///etc
}
else
cout << "words \n";
Last edited on
Hello maigistr,

PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

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>.
	}
	else if (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.

Hope that helps,

Andy
Topic archived. No new replies allowed.