Validate Integers and Accept only if with a certain range

I have written this block of code and I don't seem to understand why it is not working. I have tried using a while statement and if statement but that has not worked out so far.

When I input 100 for closing time or 100 for opening time it simply accepts them. Can anyone point out what I am doing wrong in the code and maybe a better method to write it since I will be using the same code for 3 different stations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  ofstream outputFile;
	outputFile.open("SelangorOperationHours.txt");

	int SelangorOpening; // changed to int instead of string
	int SelangorClosing; // changed to int instead of string 

	do
	{
		cout << "Opening hour has to be an valide number which is greater then 0 and less then 24.\n\n";
		cout << "Enter Opening Hours for Selangor Railway: ";
		cin >> SelangorOpening;

		cout << "Closing hour has to be an valide number which is greater then 12 and less then 24.\n\n";
		cout << "Enter Closing Hours for Selangor Railway: ";
		cin >> SelangorClosing;

	} while (!(SelangorOpening > 0 && SelangorOpening < 24) && !(SelangorClosing > 12 && SelangorClosing < 24));


	outputFile << "Opening hours for Selangor Railway: " << SelangorOpening << endl;
	outputFile << "Closing hours for Selangor Railway: " << SelangorClosing << endl;
	outputFile.close();
	cout << "Successfully Registered!\n\n";
Last edited on
By using && you are saying that both variables must be outside their acceptable ranges for the loop to repeat.
I've changed the && to || and in all three yet the issue still remains, I also mixed and matched. Which && are you referring to? The logic seems to make sense.

I apologize for the late reply
Last edited on
Hello GhettoBurger,

I looked over what you are trying to do and offer this suggestion:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
do
{
	std::cout << "\nOpening hour has to be an valide number which is greater then 0 and less then 13.\n\n";
	std::cout << "Enter Opening Hours for Selangor Railway: ";
	std::cin >> SelangorOpening;

} while (SelangorOpening < 1 || SelangorOpening > 12);

do
{
	std::cout << "\nClosing hour has to be an valide number which is greater then 12 and less then 24.\n\n";
	std::cout << "Enter Closing Hours for Selangor Railway: ";
	std::cin >> SelangorClosing;

} while (SelangorClosing < 13 || SelangorClosing > 23);

Trying to do everything at one time is a nice thought, but how do you know which one is wrong. Splitting it into two you are assured to get the right value for each variable.

Just a thought.

Hope that helps,

Andy
Yep that worked thanks all for helping out.

I don't like that extra block of code, but hey if it get the job done then I'm all for it.
Topic archived. No new replies allowed.