C ++与IF语句的字符串比较?

时间:2018-05-05 02:01:06

标签: c++ compare string-comparison comparison-operators

我是C ++的新手,大约30分钟前开始使用在线课程学习。我有点困惑为什么这个字符串比较不适用于基本的数学脚本:

#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;
}

oneopertwo的值分别为1"+"1,但最后,打印出1 + 1 = 4201435。没有if / else if语句正在执行。造成这种情况的原因是什么?

1 个答案:

答案 0 :(得分:2)

您正在使用char *比较operator==。让oper成为std::string而不是

std::string oper

使用此处列出的字符串比较:http://en.cppreference.com/w/cpp/string/basic_string/operator_cmp

或者如果您需要使用char *进行限制,请使用strcmp

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

您还需要将操作数变量指向某个缓冲区,以便读取流。这有点复杂,我建议您将oper的类型更改为std::string

您所拥有的代码存在的问题是它将指针与char数组进行比较。您从输入方法获得的内容将是来自输入流的新字符串,并且永远不会与程序中的只读字符串具有相同的地址。

因为没有条件是true,所以没有分配。因此输出会导致未定义的行为

相关问题