0

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Ada
  • 1
  • 1
  • 1
    There's no input in your `playAgain` function. If there was it would wait for that input. Calling `main` in a C++ program is undefined behavior. https://stackoverflow.com/questions/2128321/can-main-function-call-itself-in-c – Retired Ninja Aug 24 '21 at 22:12

1 Answers1

1

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.

Dorin Baba
  • 1,578
  • 1
  • 11
  • 23
  • 2
    Not a good place to use recursion anyway. After a fun and long day of playing the game, the program will exhaust automatic storage. – user4581301 Aug 24 '21 at 22:34