You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中使用IF语句进行字符串比较失效的问题求助

你的C++数学脚本字符/字符串比较问题解决指南

嘿,刚学30分钟C++就敢动手写代码,这劲头超赞!咱们来一步步拆解你遇到的问题~

首先看你代码里的核心问题:

  • 未初始化指针导致的内存隐患:你声明了char *oper;,这是一个指向字符的指针,但它没有指向任何一块有效的内存空间。当你用cin >> oper的时候,程序会试图把输入的运算符写到这个指针指向的“未知区域”,这会触发未定义行为——可能程序崩溃,也可能出现奇怪的错误,这也是你后续比较逻辑出问题的根源之一。
  • 字符/字符串比较方式错误:就算指针没问题,C风格的字符串(char*)也不能直接用==来比较,因为==在这里比较的是指针的地址,不是字符串内容。如果要比较C风格字符串,得用strcmp()函数,但咱们有更简单的处理方式。

两种修正方案,选你顺手的来:

方案1:用单个char存储运算符(最适合你的场景)

因为你要的+ - * / %都是单个字符,直接用char类型就够了,简单又不容易出错:

#include <iostream>
using namespace std;

int main() {
    int one, two, answer;
    char oper; // 改成char类型,不用指针
    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 == '/') {
        // 加个判断避免除零错误
        if (two != 0) {
            answer = one / two;
        } else {
            cout << "Error: Cannot divide by zero!" << endl;
            return 1;
        }
    } else if (oper == '%') {
        answer = one % two;
    } else {
        cout << "Invalid operator!" << endl;
        return 1;
    }

    cout << "Result: " << one << " " << oper << " " << two << " = " << answer << endl;
    return 0;
}

方案2:用std::string存储运算符(适合未来扩展多字符操作符)

如果你以后想支持比如++这类多字符操作符,用std::string更合适,而且string可以直接用==比较内容:

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

int main() {
    int one, two, answer;
    string oper; // 用string代替char*
    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;

    // string可以直接用==比较内容
    if (oper == "+") {
        answer = one + two;
    } else if (oper == "-") {
        answer = one - two;
    } else if (oper == "*") {
        answer = one * two;
    } else if (oper == "/") {
        if (two != 0) {
            answer = one / two;
        } else {
            cout << "Error: Cannot divide by zero!" << endl;
            return 1;
        }
    } else if (oper == "%") {
        answer = one % two;
    } else {
        cout << "Invalid operator!" << endl;
        return 1;
    }

    cout << "Result: " << one << " " << oper << " " << two << " = " << answer << endl;
    return 0;
}

补个小知识点:

为什么原来的char*不能直接用==?因为char*是指针,oper == "+"比较的是oper指针的地址和字符串常量"+"的地址,这两个地址肯定不一样,所以永远返回false——这就是你觉得“字符串比较无法正常工作”的原因啦!

内容的提问来源于stack exchange,提问作者APixel Visuals

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:22:35