Basically, the point of this function is to take a set of student data and sort it by the student's ID number and print it out to a new file. The breakpoint seems to be occurring in the loop that writes to the output file but I am not sure because it seems like all cout statements I make after still are read to the console.
void file_score(char* infile, char* outfile)
{
int size;
ifstream fin(infile);
fin >> size;
int *student_id = new int(size);
char *grade = new char(size);
double *gpa = new double(size);
//Creates new arrays of size that is read from file.
for (int i = 0; i < size; i++)
{
fin >> student_id[i] >> grade[i] >> gpa[i];
int temp_id = student_id[i];
char temp_grade = grade[i];
double temp_gpa = gpa[i];
int j;
for (j = (i - 1); j >= 0; j--)
{
if (student_id[j] < temp_id) {
break;
}
student_id[j + 1] = student_id[j];
grade[j + 1] = grade[j];
gpa[j + 1] = gpa[j];
}
student_id[j + 1] = temp_id;
grade[j + 1] = temp_grade;
gpa[j + 1] = temp_gpa;
//Using insertion sort to sort data as its being scanned in.
}
fin.close();
ofstream fout(outfile);
for (int k = 0; k < size; k++)
{
fout << student_id[k] << " " << grade[k] << " " << gpa[k] << "\n";
}
//Print to file
fout.close();
delete []student_id;
delete []grade;
delete []gpa;
}
These statements are wrong:
int *student_id = new int(size);
char *grade = new char(size);
double *gpa = new double(size);
You are not allocating 3 arrays , you are actually allocating 3 single values . So, when your loops are trying to access the array elements afterwards, they are accessing memory incorrectly, causing undefined behavior that is likely corrupting memory.
Change those statements to this instead:
int *student_id = new int[size];
char *grade = new char[size];
double *gpa = new double[size];
A better solution is to use std::vector
instead of new[]
directly, though:
std::vector<int> student_id(size);
std::vector<char> grade(size);
std:vector<double> gpa(size);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.