My program keeps crashing and I don't know why

This program is supposed to take input from the user regarding 5 players names and levels, whenever the loop goes around the fifth time, right after the user enters the fifth players name the program crashes. I have no idea why.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <cstdlib>
using namespace std;

struct playerInfo
{
    string name;
    int level;
};

int main()
{

playerInfo player[5];

for(int i = 1; i <= 5; i++)
{
    system("CLS");
    cout << "Player " << i << " name = ";
    cin >> player[i].name;
    cout << endl;
    cout << player[i].name << "'s " << "level = ";
    cin >> player[i].level;
}

for(int i = 1; i <= 5; i++)
{
    system("CLS");
    cout << "Player " << player[i].name << " is level " << player[i].level << endl;
}


}
Out of bounds. player[5] means 0, 1, 2, 3, 4 and you are doing 1, 2, 3, 4, 5 so it is skipping [0] and filling in player [1], [2], [3], [4] and then trying to fill a player[5] that doesn't exist. Like wise you are trying to print an extra field that doesn't exist.

I'm under Ubuntu so had to change system("CLS"); to "clear" for me, but here is your code with the fixes and an added for statement to print out the whole array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include <iostream>
#include <cstdlib>
using namespace std;

struct playerInfo
{
    string name;
    int level;
};

int main()
{

	playerInfo player[5];

	for(int i = 0; i <= 4; i++)
	{
		system("clear");
		cout << "Player " << i + 1 << " name = ";
		cin >> player[i].name;
		cout << endl;
		cout << player[i].name << "'s " << "level = ";
		cin >> player[i].level;
	}

	for(int i = 0; i <= 4; i++)
	{
		system("clear");
		cout << "Player " << player[i].name << " is level " << player[i].level << endl;
	}
	system("clear");
	for(int i = 0; i <= 4; i++)
	{
		cout << "Player " << player[i].name << " is level " << player[i].level << endl;
	}

}
Last edited on by closed account z6A9GNh0
Ah such a silly mistake, thank you!
Topic archived. No new replies allowed.