Duxa
Duxa

Reputation: 1008

How to properly return an operator (*,/,-,+) in C++?

EDIT - thank you all for the help. I didnt even think of doing the switch statement. For some reason I keep thinking C++ is a lot different than Java... it makes a lot of sence with a switch.. thanks for bringing that to my attention.

How would I properly return an operator and use it once returned? I wrote a function to grab the operator from the input and check to make sure that its valid input.. this is the code I wrote for that (i called it doctor because I guess operator is a reserved name in C++ and doctors do operations haha... sorry.. just being silly)...:

string doctor()
{
    string getDoc;

    cin >> getDoc;

    if (getDoc == "*")
        return "*";

    if (getDoc == "/")
        return "/" ;

    if (getDoc == "-")
        return "-" ;

    if (getDoc == "+")
        return "+" ;

    else 
    {
        cout << "You entered " << getDoc << " please only use +,-,*,/ : ";
        return doctor();
    }
}

when the value is returned I have my main () do the following (it returns it into the "operation" variable...:

cout << firstNum << operation << secondNum << " is " << answer;

I have everything working except for that operator... how do I make that do what it needs to do.. in other words if its a * then multiply etc...

sorry if this is basic, but I am new to C++, and googling for this didnt yield results...

thanks!

Upvotes: 3

Views: 287

Answers (7)

Dirk
Dirk

Reputation: 1849

write another method doing your calculations and call it:

float doDoctoryStuff(float a, float b, const char op)
{
  switch(op) {
    case '*':
      return a * b:
      break;
    ...
    ...
    ...
 }
}

in your main

cout << firstNum << operation << secondNum << " is ";
cout << doDoctoryStuff(firstNum, secondNum, doctor().c_str());

Upvotes: 0

spin_eight
spin_eight

Reputation: 4025

usage of doctor(operator) depends on operands, if they are instances of classes - you have to overload operator for them, otherwise I think you can write one function per operator which takes 1,2,3 arguments. When use switch statement in which according to the value of operation needed function is called and needed result is returned

Upvotes: 0

SvenS
SvenS

Reputation: 795

You could do the operation just like you already did the validation, i.e.

if (operation == "*")
    answer = firstNum *secondNum;

etc. (or better yet, do both in switch-cases, like proposed by my fellow answerers), though a better approach would be to create a class that parses the string and stores the operator information (as an enum) internally. Give it a method that applies the operation on two numbers and returns the result, and implement another method to return the textual representation as a string. Then you have decoupled your data from the visual presentation. (Don't forget the method that takes a string and extracts the desired operator from it ;))

Upvotes: 0

Vesper
Vesper

Reputation: 18747

A classic approach is to use switch-case construction here. You are given an '*', multiply arguments, if you're given a '/', then divide.

double doctored(char operation, double arg1, double arg2) {
    switch (operation) {
        case '+': return arg1+arg2;
        case '-': return arg1-arg2;
        case '*': return arg1*arg2;
        case '/': return arg1/arg2;
        default:  // ignore
            return arg1;
    }
}

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145279

From the returned string, you can choose a function or callable object (functor). For example, you can use if-else for that, or you can use a std::map. Then with the function or callable object, just call it.

Upvotes: 0

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

You can case it the same way you have done in the function getting the input stream:

float result;
switch(operation) {
    case '*':
        result = firstNum * secondNum;
        break;
    case '/':
        result = firstNum / secondNum;
        break;
    case '+':
        result = firstNum + secondNum;
        break;
    case '-':
        result = firstNum - secondNum;
        break;
}
cout << firstNum << operation << secondNum << " is " << result;

Upvotes: 0

dreamzor
dreamzor

Reputation: 5925

Well, you have to compare chars anyway. But the shorter way is to use (if you have sign in char)

switch(sign) { 
    case '*':
    case '/':
    case '+':
    case '-':
        string str; str += sign;
        return str; 
    default:
        return "error message";
}

OR

if(sign == "+" || sign == "-" || sign == "/" || sign == "*")
    return sign;
else
    return "Error message";

Upvotes: 2

Related Questions