Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Switch Statement

Recently (yesterday hah) I started learning C++. I am trying to make a simple calculator to practice. I used a switch statement in order to call upon the correct method(or is it function.. don't know the nuances of c++...) within the class;

However, the code will not compile because I am using a string to define which case to use and also defining multiple classes to have the same result.

Here is the switch statement (I've only done addition to squash any bugs before I add the others):

switch(input){
        case 'A': case 'a': case 'add': case 'Add':
            cout << bo.addNum();
            break;
        default:
            cout << "Not addition";
            break;
    }

The error I'm getting is the following:

basic.cpp:41:2: error: statement requires expression of integer type ('string'
      (aka 'basic_string<char, char_traits<char>, allocator<char> >') invalid)
        switch(input){
        ^      ~~~~~
basic.cpp:42:28: warning: multi-character character constant [-Wmultichar]
                case 'A': case 'a': case 'add': case 'Add':
                                         ^
basic.cpp:42:40: warning: multi-character character constant [-Wmultichar]
                case 'A': case 'a': case 'add': case 'Add':
                                                     ^

Here is the code in its totality:

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

class beckahClass{
public:
    void setNum(int num1, int num2){
        a = num1;
        b = num2;
    }
    int addNum(){
        return a + b;
    }
    int subNum(){
        return a - b;
    }
    int divNum(){
        return a / b;
    }
    int multNum(){
        return a * b;
    }
private:
    int a, b;
};

int main (void){
    beckahClass bo;
    string input;
    int a, b;

    cout << "Please specify the operation to preform by the following:\n A: add\nS: subtract\nM: Multiple\nD: divide\nEnter operation:  ";
    cin >> input;

    cout << "Enter the two nums you want to preform your operation on: ";
    cin >> a >> b;
    bo.setNum(a, b);

    switch(input){
        case 'A': case 'a': case 'add': case 'Add':
            cout << bo.addNum();
            break;
        default:
            cout << "Not addition";
            break;
    }   
    return 0;
}

I also realize there are probably more efficient ways to use logic; because I'm just starting C++, I would greatly appreciate any critique. I had been looking up 'maps' before briefly and was wondering if this might be a good instance to use it in?

Thanks.

like image 843
beckah Avatar asked Nov 23 '13 15:11

beckah


3 Answers

The reason is that C/C++ switch statement takes an int argument and do not support string as a type. Although it supports the notion of constant array. Also to mention that C/C++ switch statements are typically generated as branch tables. and it is not easy to generate a branch table using a string style switch.

In C++ the switch statement takes int as the argument.

Why you cannot string in switch and getting the below error?

basic.cpp:42:28: warning: multi-character character constant [-Wmultichar]
                case 'A': case 'a': case 'add': case 'Add':
                                         ^
basic.cpp:42:40: warning: multi-character character constant [-Wmultichar]
                case 'A': case 'a': case 'add': case 'Add':

The reason is because to generate the code for switch the compiler must understand what it means for two values to be equal. For int and enum, it is trivial and easy as they are constant values. But when it comes to string then it is difficult resulting in error.

like image 158
Rahul Tripathi Avatar answered Sep 23 '22 15:09

Rahul Tripathi


In C++, the switch statement takes an int argument, and you are trying to use it with a string, which you can not do in C++.

In this specific case, I'd argue that what you're trying to do with your switch is far to simple and an if else block would be better (plus it'd actually work with string).

For example:

if(input == "A" || input == "a" || input == "add" || input == "Add") {
    cout << bo.addNum();
} else {
    cout << "Not addition";
}

Alternatively, as others have explained, you can switch on a char. As it turns out, you can access the individual characters of a string quite nicely. This method will have your switch statement work on the first character of the string you took as input.

switch(input[0]) {
    case 'A': case 'a':
        //stuff
        break;
    case 'S': case 's':
        //stuff
        break;
    //and so on
    default:
        //stuff
        break;
}

Just keep in mind that if you do it this way, you're going to enter case 'A': case 'a': whether the user types A, a, add, Add, addition, Addition, ADD, or Apples, or alphabet, or anything that starts with an a.

like image 35
nhgrif Avatar answered Sep 25 '22 15:09

nhgrif


welcome to the world of C++, hope you enjoy.

Anyway let's talk about your problem. Firstly, methods and functions are synonymous.

Secondly, the single quote is used around a single character and double quotes are used around a string. As in I have a string "Rabbiya" that consists of characters 'R','a','b','i','y'. Get it? So you write "add" and 'a' like that in the code. Get it?

Also in the switch statement, you are using two DIFFERENT data types to check the condition, one is a character and the other is a string. "add" and "Add" are strings and 'a' and 'A' are chars. Which is wrong. Cases have the values that the argument of the switch statement can or may take. And the argument will obviously be a variable of a particular type, we will get to that.

The data types of the CASES must be the same as that of the ARGUMENT of switch - statement. Here's one thing you can do, instead of keeping char or string, you ask the user to identify the operation they perform using a number instead. Like

int a = 0;
cout << Enter: 1 for Add\n2 for Sub\n3 for Div\n4 for Sub: ";
cin >> a;

Then u use switch(a) statement with cases : case:1, case:2 and so on.

Here it will be good to have a default case too so that if an invalid input is provided, it generates an error message.

One more thing, in the class, you have two data members namely a and b. You will need to initialize these too! Otherwise you will get errors or garbage values depending on the compilers. For this purpose, you write class constructors. What are constructors? They help you initialize data members of a class object. For this purpose you should refer to this link: http://www.learncpp.com/cpp-tutorial/85-constructors/

http://www.learncpp.com/ will help you a lot throughout your course!

like image 26
Rabbiya Shahid Avatar answered Sep 25 '22 15:09

Rabbiya Shahid