I can input names and gpa, but when I finished inputting names and gpas, it will crash. Help
#include <iostream>
#include <algorithm>
#include <string>
#include <iomanip>
using namespace std;
//Program that will rearrange the input into alphabetical order
for(unsigned int i =0;i<5;i++){
for(unsigned int j =0;j<5;j++){
if(name[j]>name[j+1]){
swap(name[j],name[j+1]);
swap(gpa[j], gpa[j+1]);
}
}
}
//Output of the input(sorted in alphabetical)
cout<<"Name"<<setw(30)<<"GPA\n";
for(int i =0;i<5;i++){
cout<<endl<<name[i];
cout<<setw(30)<<gpa[i];
}
This is going to produce undefined behaviour which may or may not crash your code (and is definitely wrong). The value j=4 will be the last in the loop, but then j+1=5 and name[] has the five elements name[0] ... name[4]. Just change the 5 to a 4 in the first of these lines. (Actually, bubble sort can be made more efficient by reducing the size of these loops and checking for any swaps at all, but that's for another day.)