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

国际象棋终端程序异常退出:黑方回合条件判断逻辑失效

问题根源分析

你的代码逻辑错误出在std::string::find的返回值判断上:

  • std::string::find找不到目标字符时,返回的是std::string::npos(这是一个无符号类型的常量,值极大,转换为布尔值时为true);
  • 你写的if(move.find('#')),在黑方输入不包含#时,find返回npos,条件为真,会执行mated = true,跳过else if(!mated)的跳转逻辑,导致程序直接退出。
  • 就算输入包含#,如果#在字符串开头(索引0),find返回0,条件为假,也不会触发mated = true,逻辑完全颠倒。
修复方案

把判断条件改成检查find的返回值是否不等于std::string::npos,这才是正确判断字符串是否包含目标字符的方式。修复后的代码如下:

#include <iostream>

int main(){
    bool turn = true;
    int turnNumber = 0;
    bool mated = false;

    label:
    while(turn){

        std::string move;
        std::cout << "White to move: ";
        std::cin >> move;
        std::cout << move << '\n';
        turn = false;
    }

    while(!turn){

        std::string move;
        std::cout << "Black to move: ";
        std::cin >> move;
        std::cout << move << '\n';
        turn = true;
        turnNumber+=1;

        if(move.find('#') != std::string::npos){ // 修正判断条件
            mated = true;
        }

        else if(!mated){
            goto label;
        }
    }
}

额外提一句:你用goto加嵌套while的写法可以优化,比如用一个外层循环控制回合交替,避免goto,但这属于代码风格问题,核心bug还是find的判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:17:13