Reputation: 91
Please help! I can't produce the output of my program. This is the condition: Construct a program that gives a discount of 100 pesos if the shirt bought is XL and the the price is greater than 500; and a discount of 50 pesos if the shirt bought is L and the price is greater than 600.
#include <iostream>
using namespace std;
int main()
{
int p;
int s;
cout << "Input price: ";
cin >> p;
cout << "Input size: ";
cin >> s;
switch (s)
{
case 'XL': case 'xl':
{
if (p>500){
cout << "Total price: " << p-100 << " pesos.";
break;
}
else if ((s=='XL' || s=='xl') && (p<500)){
cout << "Total price: " << p << " pesos.";
break;
}
}
case 'L': case 'l':
{
if (p>600){
cout << "Total price: " << p-50 << " pesos.";
break;
}
else if ((s=='XL' || s=='xl') && (p<600)){
cout << "Total price: " << p << " pesos.";
break;
}
}
case 'M': case 'm':
{
cout << "Total price: " << p << " pesos.";
break;
}
case 'S': case 's':
{
cout << "Total price: " << p << " pesos.";
break;
}
}
return 0;
}
The output of the program:
Input price: 500
Input size: XL
Process returned 0 (0x0) execution time : 5.750 s
Press any key to continue.
P.S. How can I remove the warning (multi-character character constant) in my program? Thanks in advance!
Upvotes: 7
Views: 123655
Reputation: 254691
If the size can be more than a single character, then you'll need to represent it with a string. You can't switch
on a string, so you'll have to use if..else..else..
to deal with the value:
std::string size;
cin >> size;
if (size == "XL") {
// deal with size XL
} else if (size == "L") {
// deal with size L
} // and so on
If it were a single character, then you could use char
(not int
) to represent that:
char size;
cin >> size;
switch (size) {
case 'L':
// deal with size L
break;
// and so on
}
but for multiple characters, you'll need a string.
Upvotes: 12
Reputation: 2119
switch
statement can handle int
and char
in C++. char
data type can hold only one letter. Thus, if you input only one letter (X
) for XL size will be fine ...
cout << "Input size (X/L/M/S): ";
cin >> s;
switch (s){
case 'X': case 'x':
Upvotes: 5
Reputation: 5833
You've declared s
as an integer but attempt to use it as a character and character array. You should probably declare it is char s;
and then use it consistently as just a single character -- which does mean that you can't check for XL
. You could, however, just check for X
in your switch.
If you absolutely must check for XL
, then you'll need to use either a character array or std::string
, although switch statements can only be used with single characters, so you may have to nest your switch to check for multiple characters or just use a series of if (strncmp(...)...)
calls.
Upvotes: 0