0

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

}

2 Answers2

3

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

}
Sachin
  • 40,216
  • 7
  • 90
  • 102
  • Just to explain it a bit more for OP's benefit: arrays in C++ are `[0, length[` contrary to some other languages where they are `[1, length]` (note the interval's end `[` or `]` which is important -- excluded or included). – syam Apr 19 '13 at 23:29
  • wow, did not notice I made that mistake, thanks. Guess I'm just too used to counting from 1. –  Apr 21 '13 at 00:36
2

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?

Community
  • 1
  • 1
masotann
  • 901
  • 10
  • 29
  • +2 for the GOTO remark, but a definite -1 for failing to notice the 1-based indexing (which should be 0-based in C++ of course). The termination condition is not enough, the starting condition (a=0/1) means a lot too. I guess this all boils down to +1... ;) – syam Apr 19 '13 at 23:35
  • thanks for the goto comment, did not know it was bad in any way. –  Apr 21 '13 at 00:37