ShiviRox
ShiviRox

Reputation: 425

Why am i getting this error? binary '==' : no operator found which takes a left-hand operand of type 'std::string'

I don't know why I'm getting this compile error. I tried the usual way to define strings and i also tries std::string but neither worked. Also I think there might be a problem with how I'm trying to print the function.

#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>

float userInput1() // Defines the inputs from the user
{
using namespace std;
    cout << "Please enter first number" << endl;
    float number1;
    cin >> number1;

    return number1;
}

float userInput2() // Defines the inputs from the user
{
using namespace std;
    cout << "Please enter second number" << endl;
    float number2;
    cin >> number2;

    return number2;
}

std::string getOperation()
{
using namespace std;
    cout<<"Please enter the operator. + - * /" << endl;
    std::string userOperator;
    cin>>userOperator;

    return userOperator;
}

float computeValue(float value1, float value2, std::string operation)
{
using namespace std;

    if(operation == '+')
    {
        cout<< value1 + value2<< endl;
    }else if(operation =='-')
    {
        cout<< value1 - value2<< endl;
    }else if(operation =='*')
    {
        cout<< value1 * value2<< endl;
    }else if(operation == '/')
    {
        cout<< value1 / value2<< endl;
    }else
    {
        cout<< "Please enter: + - * /"<< endl;
    }
    return 0;
}


int main(){
using namespace std;

    computeValue(userInput1(), userInput2(), getOperation());

return 0;
}

Upvotes: 2

Views: 1568

Answers (2)

David G
David G

Reputation: 96790

The problem is that you're comparing the string object to a character in your computeValue function. There no overload of operator == in the std namespace which takes both a std::string and a char, hence the error.

You should be using char instead of a std::string if you only need a character as input.

char getOperation()
{
    std::cout << "Please enter the operator. + - * /" << std::endl;
    char userOperator;
    std::cin >> userOperator;

    return userOperator;
}

Your parameter should also take a char:

float computeValue(float value1, float value2, char operation)
//                                              ^^^^

Upvotes: 1

Dai
Dai

Reputation: 155045

You're comparing std::string with a char value using the == operator. The standard library does not define an equality operator between those two types. The list of valid comparisons is here: http://www.cplusplus.com/reference/string/string/operators/

The simplest way is to convert the char values into char* by using " instead of ', like so:

 if(operation == '+')

becomes

 if(operation == "+")

Upvotes: 1

Related Questions