C++ 代码:接受用户输入后不进行处理

C++ code: No processing after taking user input

我正在通过一门课程学习 C++,当我自己学习和复制部分代码时,我注意到当我要求用户输入并存储在一个数组中(不使用它进行打印)时,代码确实不进行下一步。

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

我只是得到输出:

/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)

但是,如果我删除要求用户输入的这一部分。然后我得到最后一部分:

/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

任何线索为什么它不前进到最后从而结合上述两个输出?

这里:

string playerName[2];

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

你有一个包含两个字符串的数组,但是在

cin >> playerName[2];

您正试图将字符串存储在数组的第 3 个元素中,该元素不存在。

应该是:

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