Search code examples
c++c++14clion

C++ code: No processing after taking user input


I am learning C++ through a course and as I followed along and replicating parts of the code myself, I noticed that when I ask for user input and store in an array (not using it for printing), the code does not proceed to the next step.

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;
    
const int MAX_CHIPS = 100;
const float MAX_TURN = 0.37;

int main()
{    
    bool player1Turn = true;  
    bool gameOver = false;

    int chipsInPile = 0;
    int chipsTaken = 0;    
    string playerName[2];

    cout << "Player 1, Enter your name: \n";
    cin >> playerName[1];
    cout << "Player 2, Enter your name: \n";
    cin >> playerName[2];
    
    //seed the random number generator
    srand(time(0));

    //start the game with a random number of chips in the pile
    chipsInPile = (rand() % MAX_CHIPS) + 1;
    cout << "This round will start with " << chipsInPile << " chips in the pile\n";
    cout << "You can only take " << static_cast<int>(chipsInPile * MAX_TURN) << endl;

    return 0;
}

I just get as output:

/home/ubuntu/CLionProjects/Temp/cmake-build-debug/Temp

Player 1, Enter your name: Stack

Player 2, Enter your name: Overflow

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

However if I remove this part asking for user input. Then I get the last part:

/home/ubuntu/CLionProjects/Temp/cmake-build-debug/Temp

This round will start with 57 chips in the pile

You can only take 21

Process finished with exit code 0

Any clue why it doesn't advance until the end thus combining both the above outputs?


Solution

  • Here:

    string playerName[2];
    
    cout << "Player 1, Enter your name: \n";
    cin >> playerName[1];
    cout << "Player 2, Enter your name: \n";
    cin >> playerName[2];
    

    You have an array with two strings, but in

    cin >> playerName[2];
    

    You are trying to store the string in the 3rd element of the array, which doesn't exist.

    It should be:

    cout << "Player 1, Enter your name: \n";
    cin >> playerName[0];
    cout << "Player 2, Enter your name: \n";
    cin >> playerName[1];