Input Validation

Hey,
So, in my program I have to take a start time, the length of the call and the rate in order to output it to the user. The only problem I have is validating the input to make sure the start time doesn't go over .59 (HH.MM format) in any instance. I was thinking about just putting a '&& < 0.59' into the if statements, but then I thought it would hurt the first part. Or am I thinking wrong? Here's my code anyway...

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
#include <iostream>
#include <conio.h>

using namespace std;

int main() //Program to calculate how much long-distance calls would be for differing lengths of time and certain starting times
{
	float start;
	float rate;
	int minutes;
	//Call start times displayed as HH.MM
	cout << "Enter what time the call was started (in HH.MM format): ";
	cin >> start;
	
	if (start >= 00.00 && start <= 06.59)
	{ 
		rate = 0.05;
	}
	else if (start >= 7.00 && start <= 19.00)
	{
		rate = 0.45;
	}
	else if (start >=19.01 && start <= 23.59)
	{
		rate = 0.20;
	}

	cout << "\nNow enter how long the call was in minutes: ";
	cin >> minutes;
	
	cout << "\nThe charge for this phone call was $" << rate * minutes << ".";		

	_getch();
	return 0;
}
You should not be storing time in numeric types. Numeric types are not appropriate for storing dates or times in a human-readable format. You can store each part of the time separately in numeric types, but what you are doing currently will only cause you more problems.
So what do you mean? Should I just store HH and MM separately and then in the if/else if statements, just designate them sorta the same? Like...
1
2
3
4
int hh;
int mm;

if (hh >= 0 && hh <= 6 && mm >= 00 && mm <= 59)
Last edited on
Yes, though be careful about starting a numeric literal with 0 - that makes the compiler treat it as octal instead of decimal.
Another question, how would I have the user input the data because the input has to specifically in HH.MM form.
You could validate it with regex if your compiler supports C++11, or you could just validate it by hand using std::isdigit. After you validate it, then you can just use a std::istringstream to read the number, ignore the period, and read the other number.
Topic archived. No new replies allowed.