Hey guys. I wanted to do a simple console program to test my abilities since I started programming like 4-5 days ago. I wanted to make a program that changed the console text and background colour using system("color"); (PLEASE DON'T TELL ME TO NOT USE SYSTEM COMMANDS I'm doing this to test out my abilities and mess around) and basically the console outputs "What text colour would you like? 1. *random color*\n2. *random color*" all the way up to 8. I wanted to create an int function that used a switch instruction and my code is unfinished below because I tried it and it doesn't work properly, basically case 1 works fine, it turns the text into grey/gray, but the rest just keep turning it into gray, so I'm assuming it doesn't even reach those cases. Is it something to do with the ( a > 0 )? If so, what else can I use? Thanks! :)
1 2 3 4 5 6 7 8 9 10 11
int coloretesto(char a)
{
switch (a > 0)
{
case 1: system("color 8"); break;
case 2: system("color 9"); break;
case 3: system("color a"); break;
case 4: system("color B"); break;
}
return a;
}
Review how switch statements work. What values do you think you're switching on when you say this? switch (a > 0)
The only values that the expression a > 0 can evaluate to are true and false. In your case, every character you enter resolves to a code point greater than zero, so a > 0 resolves to true. You can think of C++ doing an implicit integer conversion of true to 1, so case 1 is always run. You should instead say switch(a)
Ty soooo much! I was going crazy! The funny thing is I tried everything you guys told me but I just did it all seperately, like I tried to change the switch back to (a) again and it didn't work, then I tried the '1' but I switched it back to a > 0, never thought of doing both haha... ty sooo much!