user2300929
user2300929

Reputation:

How do I use cin in a while loop?

I'm trying to get the user to input their name(s) using a while loop with an array and cin, but after the last person's name is input, the program crashes instead of moving on. Is there a way to fix this, or do I need to completely change up the code? I'm also fairly new to c++, so can any answers be given as simply as possible?

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

}

Upvotes: 0

Views: 3863

Answers (2)

masotann
masotann

Reputation: 911

Your last iteration exceeds the size of the array. You need to change it to

while(a < numberofplayers)

also, on another note, the keyword goto isn't used much anymore. I would suggest using a while there also like

while(true){
    cout<<"number of players";
    cin>>numberofplayers
    if(numberofplayers is valid input){
        break;
    }
    cout<<"bad input";
}

There is a question on stackoverflow discussing the use of goto extensively here: GOTO still considered harmful?

Upvotes: 2

Sachin
Sachin

Reputation: 40970

You would probably facing array index out of bound, so Change you while loop to this and set a=0 to fill from 0th index.

while(a < numberofplayers){

}

Upvotes: 3

Related Questions