It has something to do with the lines at the bottom of the code. Can anyone help me? It doesnt cout anything. The program just crashes upon execution. First, it asks me the amount of students i want to handle. I enter '1'. Then it asks me if i want to read in from external file and i enter 'Y'. then the exe just crashes, can anyone help?
#include <iostream>
#include <cstddef>
#include <cstdlib>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct Date
{
int day, month, year;
};
struct Grade
{
int score[6];
};
struct Student
{
bool free;
long studentID;
string fname;
string sname;
Date DOB, DOE, DOG;
Grade semester1, semester2;
};
void initialise_database(vector<Student>, int size); // initialize each free variable to free
int menu();
void add_students(vector<Student>, int size);
void display_students(vector<Student>, int size);
int main(int argc, char** argv)
{
fstream fin;
char choice_readfile;
int rowcount;
int size;
cout << "Enter number of students that you wish to keep in record:\n";
cin >> size;
vector<Student> BENG;
do //verify choice to read from file is Y,y or N,n
{
cout << "Do you wish to read from file (Y/N)? (file name must be named students.txt)" << endl; //choice for user to read from external file
cin >> choice_readfile;
while(cin.fail())
{
cin.clear();
cin.ignore(80,'\n');
cout << "Please Re-Enter choice" << endl;
cin >> choice_readfile; // choice to read from file
}
}
while(choice_readfile != 'Y' && choice_readfile != 'y' && choice_readfile != 'N' && choice_readfile != 'n');
1) while(!fin.eof()) reads one more time than needed. Do not loop on eof() it does not work like you think. Loop on input operation, or save input in temporary variable and check stream after input.
2) fin >> BENG[i]/*...*/ Your BENG vector contains 0 elements. Precondition for operator[] is that its argument should be non-negative(actually it cannot be negative as it is unsigned) number less than vector size.
Attempt to use invalid index will lead to undefined behavior. You got lucky and your program just crashed.
3) you should not pass vectors by value and expect changes to it reflect on original vector. Nor you shoud pass size of vector alongside it: vector knows its size already.
4) do not threat vectors as arrays. You can remove values from it, add values to it, request size, and use all of this without need to manually resize vector or mark values as "deleted"
Avoid monolitic code. Separate it in logical parts and reuse them in your code. C++ features: constructors, operator overloading, etc, will help you with this.
Rule of thumb: if a function does not fit on screen, it is too large.
For example several functions from your code after slight refactoring: