#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int array1 [70];
string array2 [1000];
void numgenerate (void)
{
int marks,count;
for (count=0 ; count<71 ; count++)
{
marks = rand() % 101;
array1 [count] = marks;
if(marks>=82)
array2 [count]="A+";
else if(marks>=74 && marks<81)
array2 [count]="A";
else if(marks>=66 && marks<73)
array2 [count]="B";
else if(marks>55 && marks<65)
array2 [count]="B-";
else if(marks>=68 && marks<55)
array2 [count]="C";
else if(marks>=61 && marks<68)
array2 [count]="C-";
else if(marks>=54 && marks<61)
array2 [count]="D";
else
array2 [count]="F";
}
}
void createfile (void)
{
numgenerate();
ofstream file( "G:\\student grade and number file.txt", ios::out );
if(!file)
{
cerr << "File could not be opened" << endl;
exit( 1 );
}
for (int count=0 ; count<=70 ; count++)
{
file<<setw(4)<<array1 [count]<<" "<<array2 [count]<<endl;
}
}
void main ()
{
createfile();
system ("pause");
return ;
}
I keep getting the following error
Unhandled exception at 0x61ee797f (msvcp90d.dll) in NEW PROJECT.exe: 0xC0000005: Access violation writing location 0x0000004b.
Can anyone tell me why i keep getting this error and how to correct my code if you can please you will be of great help.
The exit condition of your for
loop
for (count=0 ; count<71 ; count++)
should be
for (count=0 ; count<70 ; count++)
In this way, when count == 70
, the loop is not executed. If you execute your loop with count == 70
, you are out of bounds of your array, whose length is 70 (elements from 0 to 69).
As LumpN pointed out, also the second loop is wrong:
for (int count=0 ; count<=70 ; count++)
Even in this case you are trying to write out of array bounds as the loop is executed also when count == 70
Valid indecies for the first array are 0 - 69 because the array has 70 elements. So the following loops are invalid
for (count=0 ; count<71 ; count++)
for (int count=0 ; count<=70 ; count++)
Must be
for ( int count = 0 ; count < 70 ; count++ )
Also it is a good idea to define corresponding constant naming this magic number. For example
const int N = 70;
and then in loops to use this constant
for ( int count = 0 ; count < N ; count++ )
Also function main shall have return type int
int main()
Also I see a contradiction in the conditions of the following if-else statements
if(marks>=82)
array2 [count]="A+";
else if(marks>=74 && marks<81)
array2 [count]="A";
else if(marks>=66 && marks<73)
array2 [count]="B";
else if(marks>55 && marks<65)
array2 [count]="B-";
else if(marks>=68 && marks<55)
array2 [count]="C";
else if(marks>=61 && marks<68)
array2 [count]="C-";
else if(marks>=54 && marks<61)
array2 [count]="D";
else
array2 [count]="F";
Compare for example marks B- and C.
User contributions licensed under CC BY-SA 3.0