Search code examples
c++comparestring-comparisoncomparison-operators

String Comparison in C++ with IF Statements?


I'm very new to C++, just started learning using an online course about 30 minutes ago. I'm a little confused as to why this string comparison isn't working in a basic math script:

#include <iostream>
#include <string>
using namespace std;

int main() {
  int one, two, answer;
  char *oper;

  cout << "Add two numbers\n\nEnter your first number" << endl;
  cin >> one;
  cout << "Choose an operator: +  -  *  /  %%" << endl;
  cin >> oper;

  cout << "Enter your second number" << endl;
  cin >> two;

  if (oper == "+") {
    answer = one + two;
  }
  else if (oper == "-") {
    answer = one - two;
  }
  else if (oper == "*") {
    answer = one * two;
  }
  else if (oper == "/") {
    answer = one / two;
  }
  else if (oper == "%%") {
    answer = one % two;
  }

  cout << one << " " << oper << " " << two << " = " << answer << endl;

  return 0;
}

The values for one, oper, and two are 1, "+", and 1 respectively, but in the end, 1 + 1 = 4201435 is printed out. None of the if/else if statements are being executed. What's causing this?


Solution

  • You're comparing char * using operator==. Either let oper be a std::string instead

    std::string oper

    To use the string comparison listed here: http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp

    or if you need to use a char * for some restriction, use strcmp:

    if (!strcmp(oper, "+")) {
    // ...
    

    You also need to have your operand variable point at some buffer too, for the stream to read into. This is a little bit more complicated and I just recommend changing the type of oper to std::string.

    The problem with the code you have is that it's comparing pointers to char arrays. What you get from your input methods is going to be a new string from the input stream and will never have the same address as the readonly strings in your program.

    So since none of the condition is true, ans hasn't been assigned. So output it accounts for an undefined behavior.