C++ while loop question

Hi, I'm trying to get this program to loop until ether c or C is input but it isn't working? Any advice would be appreciated loops have always confused me for some reason.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main()
{
	int miles, type, Days, amount, cost{};
	
		char cartype;
		cout << "Welcome to Apex Auto Rentals Please enter the required informatin \n" << endl;
		cout << "what class of car would you like? (C for compact L for Luxory) \n" << endl;
		cin >> cartype; // user enters car type 
			switch (cartype) {  
			case 'c':
			case 'C':
				amount = 17;
				break;
			case 'l':  
			case 'L':
				amount = 20;
			default :
				cout << "invalid entry please try again" << cartype << "\n";
			}while (cartype != 'C' && cartype != 'c')
Do you mean this:

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
#include <iostream>

int main() {
	int miles, type, Days, amount, cost {};
	char cartype {};

	std::cout << "Welcome to Apex Auto Rentals Please enter the required information\n";

	do {
		std::cout << "What class of car would you like? (C for compact L for Luxury): ";
		std::cin >> cartype;

		switch (cartype) {
			case 'c':
			case 'C':
				amount = 17;
				break;

			case 'l':
			case 'L':
				amount = 20;
				break;

			default:
				std::cout << "invalid entry please try again" << cartype << "\n";
				break;

		}
	} while (cartype != 'C' && cartype != 'c');
}

1
2
3
4
while (/* condition to decide if the loop should continue running */)
{
	// code that you want to repeat
}
I think what you are trying to do is restrict the input char options to only C/c/L/l, and to continue to run the while loop if any other char (other than C/c/L/l) has been entered.

This will continue to run the loop (ask the user to re-enter) for any other char except for C/c/L/l.

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

#include <iostream>

int main() {
	int miles, type, Days, amount, cost {};
	char cartype {};

	std::cout << "Welcome to Apex Auto Rentals Please enter the required information\n";

	do {
		std::cout << "What class of car would you like? (C for compact L for Luxury): ";
		std::cin >> cartype;

		switch (cartype) {
			case 'c':
			case 'C':
				amount = 17;	
				break;

			case 'l':
			case 'L':
				amount = 20;
				break;

			default:
				std::cout << "invalid entry please try again" << cartype << "\n";
				break;

		}
	} while (cartype != 'C' && cartype != 'c' && cartype != 'L' && cartype != 'l');
}
Topic archived. No new replies allowed.