Input validator

I'm trying to make it so that when the user enters anything below 0 mins it'll say that its invalid and not give a price. I know I'm supposed to use an if statement, I just don't know where I'm supposed to place it. I've tried different places, all not giving me the results that I need.

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
  #include <iostream>
using namespace std;
int main() {


	float a = 39.99;
	float b = 59.99;
	float c = 69.99;
	int min;

	int choice;

	cout <<"What is your package plan? \n"
		<< "1. $39.99 \n"
		<< "2. $59.99 \n"
		<< "3. $69.99 \n";
	cin >> choice;


	cout<< "How many minutes have you gone over?"<<endl;
	cin>>min;

	float price;



	switch(choice)
	{

		case 1:

			price = a + (.45 * min);
			cout<< "your price is "<<price<<endl;
			break;
		case 2:

			price = b + (.45 * min);
			cout<< "your price is "<<price<<endl;
			break;
		case 3:

		    price = c + (.45 * min);
			cout<< "your price is "<<price<<endl;
			break;
		default:

			cout<<"You chose an invalid section from the list or have chosen an invalid number of minutes. "<<endl;
	}

	return 0;

A good place to test would be immediately after getting the minutes from the user:

20
21
22
23
24
25
26
	cout<< "How many minutes have you gone over?"<<endl;
	cin>>min;
	if (min < 0)
	{
		cout << "Minutes cannot be negative.\n";
		return 1;
	}
Hello Ryoka117,

Some suggestions for you to consider.

Lines 6 - 8 would work better as a "constexpr" or at least a "const". These variables should not be changed by the program. Also double is preferred over float.

Line 9 it is always a good idea to initialize your variables.

Lines 32, 37 and 42 the ".45" should be a constant variable. It makes this easier to change in the future.

Just some thoughts.

Hope that helps,

Andy
Topic archived. No new replies allowed.