0

in this small chess terminal app, at the end of black's turn, the code should check if move contains '#' if so, it should exit. The problem is, it automatically exits and doesn't check the second if statement, looping it back to label. Why is this?

#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('#')){
            mated = true;
        }

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

I tried switching the statements around and removing the else, but that didn't work.

1 Answers1

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

This is your updated code. What was happening is, .find() method returns the first occurence of the given char or string. If it doesn't find one, it always return string::npos value (can be verified using this before you check that if condition):

std::cout << move.find('#') << endl;

and this value is always true. So it goes inside the if part.

The solution to it is checking with that value itself. If it is not equal to the npos value, that means the string contains '#', else not.