String in array crashes program
Nov 10, 2017 at 3:36pm UTC
I am trying to make a program that holds soccer players' name, number, and points scored for my homework, but the last string crashes the program. I will type in strings 1-11 without any problems, but string 12 will crash the program and show this error message:
Exception thrown:
write access violation.
_Left was 0xD548E61E.
Here is my code:
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct soccerScores
{
string playerName;
int playerNumber;
int pointsScored;
};
int main()
{
soccerScores player[12];
for (int i = 1; i <= 12; i++)
{
cout << "Enter player " << i << "'s name: " ;
cin >> player[i].playerName;
}
for (int i = 1; i <= 12; i++)
{
cout << "Enter player " << i << "'s number: " ;
cin >> player[i].playerNumber;
if (player[i].playerNumber < 0)
{
cout << "You cannot have a negative number!" ;
cout << "Enter player " << i << "'s number: " ;
cin >> player[i].playerNumber;
}
}
for (int i = 1; i <= 12; i++)
{
cout << "Enter player " << i << "'s points: " ;
cin >> player[i].pointsScored;
if (player[i].pointsScored < 0)
{
cout << "You cannot have scored negative points!" ;
cout << "Enter player " << i << "'s points: " ;
cin >> player[i].pointsScored;
}
}
for (int i = 1; i < 13; i++)
{
cout << "Player " << i << "'s name is: " << player[i].playerName << endl;
cout << "Player " << i << "'s number is: " << player[i].playerNumber << endl;
cout << "Player " << i << "'s points scored are " << player[i].pointsScored << endl;
}
system("pause" );
return 0;
}
Nov 10, 2017 at 4:25pm UTC
Array indexes start from 0, not 1
for (int i = 1 ; i <= 12; i++)
should be
for (int i = 0 ; i < 12; i++)
Nov 10, 2017 at 5:55pm UTC
Thank you!
Topic archived. No new replies allowed.