Help me properly nest while loops.

I need help to clean up my code. How can I combine my while loops by nesting? I was trying around and experimenting but I kept running into infinite loop issues. I'm basically validating the user to enter numbers (int and double) and I'm making the user have an error message when any letter, word, or symbol is entered. Help would be greatly appreciated. Thanks.

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
53
54
55
56
57
58
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;

int main ()
{
	int time;
	double speed;
	
	cout << "What is the speed of the vehicle in mph?" << endl;
	cin >> speed;
	 
		while(!cin)
	{
		cout << "That was not a number! Please enter a speed of 0.1 mph or more: " << endl;
		cin.clear();
		cin.ignore();
		cin >> speed;
	}

		while (speed < 0.1)
	{
		cout << "Invalid. Please enter a speed of 0.1 mph or more." << endl;
		cin >> speed;
	}
	
	cout << "How many hours has the vehicle traveled?" << endl;
	cin >> time;

		while(!cin)
	{
		cout << "That was not a number! Please enter time in terms of 1 hour or more. " << endl;
		cin.clear();
		cin.ignore();
		cin >> time;
	}

		while (time < 1)
	{ 
		cout << "Invalid. Please enter 1 hour or more." << endl;
		cin >> time;
	}

	cout << "Hour  |  Distance Traveled" << endl;
	cout << "__________________________" << endl;

	for (int hour = 1; hour <= time; hour++)
	{
		 cout << fixed << setprecision(2);
		 double distance = speed * hour;
		 cout << hour << "        " << distance << " miles." << endl;
	}

	system("pause");
	return 0;

}
Last edited on
You have used too many while loops. It is not required to use as much as you used.
You may set one while loop and in the body of while loop, you can write if statement.

I am outside so I can not write the code wright now.
Best regards.
Topic archived. No new replies allowed.