Reputation: 3
everyone! I think it could be a silly question, but I was wondering if it is possible to show a case label in a switch statement in C++. This is the statement:
switch(TYPE)
{
case 'A':
(cost <= 30000);
break;
case 'B':
(30000 < cost <= 60000);
break;
case 'C':
(cost > 60000);
break;
}
In this code, the user writes the cost at the beginning of it. The ranges that are showed in each case are the prices of a product. Let's say they write 62000, so given that it costs more than 60000 it should go to the type C product. So I would like to show the type to the user, and I write:
cout <<"TYPE: "<< TYPE <<endl;
But when I run the code, this line appears empty. I would like to find the way to put the 'C' there, which is the type that corresponds to the cost. Or at least I would like to know if this is not possible so I can think of another way to make this happen. I appreaciate your time and consideration. :)
Upvotes: 0
Views: 118
Reputation: 13589
It sounds like your logic might be a bit backwards. switch
is used to check against the value of a variable that has already been set. Additionally, it can only check a single value per case
; it cannot check a range.
If I interpret your question correctly, I think you want something like this:
if (cost <= 30000) {
TYPE = 'A';
} else if (cost <= 60000) {
TYPE = 'B';
} else {
TYPE = 'C';
}
Upvotes: 2
Reputation: 597205
You are going about this backwards. A switch
will not accomplish what you want. You need to use if..else
instead, eg:
cout << "TYPE: ";
if (cost <= 30000)
cout << 'A':
else if (cost <= 60000)
cout << 'B':
else
cout << 'C':
cout << endl;
Which you can take a step further by wrapping the logic inside a function, eg:
char getTYPE(int cost)
{
if (cost <= 30000)
return 'A':
else if (cost <= 60000)
return 'B':
else
return 'C':
}
cout << "TYPE: " << getTYPE(cost) << endl;
Upvotes: 5