Switch statement??
Jun 3, 2022 at 3:28am UTC
Hi guys, I'm putting a switch statement in a loop, for example with 3 cases as below. How do I make sure that in order to proceed with the 3rd case, 1st and 2nd options were chosen beforehand, and both containing correct values inside?
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
do {
cout << "1. Select first colour" << endl;
cout << "2. Select second colour" << endl;
cout << "3. Mix the colours" << endl;
cout << "0. Exit" << endl;
cout << "Option: " ;
cin >> option;
string colour1, colour2, colour3;
switch (option){
case 1:
cout << "First colour: " ;
cin >> colour1;
break ;
case 2:
cout << "Second colour: " ;
cin >> colour2;
break ;
case 3:
if ( ???? ){
cout << "Final colour is: " << colour3;
}
break ;
default :
cout << "Error!" << endl;
break ;
}
}while (option != 0);
Jun 3, 2022 at 4:25am UTC
How about something like 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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#include <iostream>
#include <string>
using namespace std;
string get_color()
{
string color;
cin >> color;
// perform whatever editing you want here
// if good then return color
// else return empty string
}
int main()
{
int option;
do {
cout << "1. Select first colour" << endl;
cout << "2. Select second colour" << endl;
cout << "3. Mix the colours" << endl;
cout << "0. Exit" << endl;
cout << "Option: " ;
cin >> option;
string colour1, colour2, colour3;
switch (option) {
case 1:
cout << "First colour: " ;
colour1 = get_color();
break ;
case 2:
cout << "Second colour: " ;
colour2 = get_color();
break ;
case 3:
if (colour1.empty() || colour2.empty())
{ // error
continue ;
}
// calculate colour3
cout << "Final colour is: " << colour3;
break ;
default :
cout << "Error!" << endl;
break ;
}
} while (option != 0);
return 0;
}
Jun 9, 2022 at 10:29pm UTC
Don't use a switch statement. You expect to input one number, then another, then print the final color. There's no reason for a loop or switch statement. This is straight-line code.
Topic archived. No new replies allowed.