Tuesday 8 March 2011

Switch Case using string

When I started thinking of this example, I also faced some of the other problems that I have encountered in my initial days of C++. One of these problems was how to convert String to multiple Ints and how to split strings easily, etc. Hopefully you will find the example useful.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>
#include<sstream>
#include<map>

using namespace
std;

void
split(const string& input, int& num1, int& num2, string& operation);
int
calculate(int num1, int num2, string operation);

int
main()
{

string s[5] = {"2 + 2", "4 - 1", "4 * 6", "18 / 3", "12 ^ 2"};

for
(int i = 0; i < 5 ; i++)
{

int
num1=0, num2=0;
string op;
split(s[i], num1, num2, op);
int
retVal = calculate(num1, num2, op);
cout<<s[i]<<" = "<<retVal<<endl;
}


return
0;
}


void
split(const string& input, int& num1, int& num2, string& operation)
{

istringstream iss(input);
iss >> num1;
iss >> operation;
iss >> num2;
}


int
calculate(int num1, int num2, string operation)
{

enum
Operators {unknown, add, sub, mul, div};
map<string, Operators> mapOfOperators;
mapOfOperators["+"] = add;
mapOfOperators["-"] = sub;
mapOfOperators["*"] = mul;
mapOfOperators["/"] = div;

switch
(mapOfOperators[operation])
{

case
add:
return
num1 + num2;
case
sub:
return
num1 - num2;
case
mul:
return
num1 * num2;
case
div:
return
num1 / num2;
default
:
cout<<"Unrecognised Operator "<<operation<<endl;
}

return
0;
}


The output is as follows:
See Also: Codeguru article on 'Switch on Strings in C++'.

1 comment:

  1. Good example, I just want to note that you should put some kind of check for divide by zero in your switch statement.

    ReplyDelete