我试图让用户使用带有数组和cin的while循环来输入他们的名字,但是在输入了最后一个人的名字之后,程序崩溃了而不是继续前进。有没有办法解决此问题,还是我需要完全更改代码?我对c ++还是很陌生,所以可以给出尽可能简单的答案吗?

#include <iostream>
#include <string>

using namespace std;

int main()
{
    unsigned int numberofplayers;
        number://loop back here if more than 4 players
    cout << "Number of players: ";
    cin >> numberofplayers;
        if(numberofplayers > 4 || numberofplayers < 1){
            cout << "Invalid number, please enter a number from 1 to 4." << endl;
            goto number;
        }
    string name[numberofplayers];
    cout << "Enter your name" << endl;
    int a = 1;
    while(a < numberofplayers + 1){
        cout << "Player " << a << ": ";
        cin >> name[a];
        cout << "Hello, " << name[a] << "." << endl;
        a++;
    }

}

最佳答案

您可能会面临数组索引超出范围的问题,因此将while循环更改为此,并将a=0设置为从第0个索引开始填充。

while(a < numberofplayers){

}

关于c++ - 如何在while循环中使用cin?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16114826/

10-11 12:28