Ada
Ada

Reputation: 1

Stop function from proceeding

I have this piece of code:

if (attackShip == true) {
    board[guessRow][guessCol] = "x";
    cout << "Oops, you sunk my ship!" << endl;
    numShips--;
    if (numShips == 0) {
        cout << "Shiver me timbers! You have won!" << endl;
        playAgain();
    }
    system("CLS");
    clearBoard(board, numShips, ships);

It's a battleship game, and I want to ask the user if they want to play again when all ships have been sunk. However, the system clears before anything can be done to the input.

Here's my code for playAgain:

void playAgain() {
    cout << "Play again? (y/n)" << endl;
    string enter = "";
    string yn;
    if (yn == "y") {
        system("CLS");
        main();
    } else if (yn == "n") {
        exit(0);
    }
}

My guess would be that it takes a "no input" as the input, and just continues the code? I'm not sure though.

Upvotes: 0

Views: 52

Answers (1)

Dorin Baba
Dorin Baba

Reputation: 1738

I think you're missing to read the input:

void playAgain() {
    cout << "Play again? (y/n)" << endl;
    string enter = "";
    string yn;
    cin >> yn; <============
    if (yn == "y") {
        system("CLS");
        main();
    } else if (yn == "n") {
        exit(0);
    }
}

And as Retired Ninja mentionel, don't call the main method from playAgain. Better create another method called say play and call play from both main and playAgain.

Upvotes: 1

Related Questions