Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character in Switch-Statement C++

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!

like image 786
Jemar Villareal Avatar asked Oct 09 '13 13:10

Jemar Villareal


Video Answer


2 Answers

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.

like image 79
Mike Seymour Avatar answered Sep 19 '22 14:09

Mike Seymour


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':
like image 25
Tun Zarni Kyaw Avatar answered Sep 23 '22 14:09

Tun Zarni Kyaw