Reputation: 51
My program crashes unexpectedly when I try and output my results to a .txt
file.
Basically, I want to store a list of students in a .txt
file and retrieve them for later convenience. My program can store the values as variables, however the moment you want to save them to the output file, the program itself crashes.
This is my code
//STUDENTS CLASS
char** studentNames;
int numberOfNames;
void Students::setNumberOfNames(int namenumbers) // Takes in the number of student names to store
{
numberOfNames = namenumbers;
}
void Students::setStudentNames() // Takes a number of student names and stores them.
{
char studentinput[128]
studentNames = new char*[numberOfNames];
for (int i=0; i<=numberOfNames; i++)
{
studentNames[i] = new char[128];
cout << "Student " << i << ": " << "\n";
cin.getline(studentinput, sizeof(studentinput));
strcpy(studentNames[i], studentinput);
}
}
//MAIN CLASS
Student s;
int nums;
int main()
{
cout << "How many names would you like to store? " << endl;
cin >> nums;
s.setNumberOfNames(nums):
s.setStudentNames();
for(int i=0; i<=s.numberOfNames; i++)
{
cout << s.numberOfNames [i] << "\n"; // THIS WORKS FINE! DOES WHAT I SAY :)
}
// THIS IS WHERE IT CRASHES. I TRY AND STORE THE NAMES INTO THE `.txt` FILE.
//IF YOU WANT TO STORE 3 NAMES, IT WORKS FINE, BUT IF YOU WANT TO STORE LIKE
//12 NAMES THE WHOLE THING CRASHES. WHEN I COMMENT OUT THE BOTTOM BLOCK
//OF CODE THE PROGRAM WORKS FINE, BUT I WANT TO STORE THE NAMES.
ofstream outputFiles ("example.txt");
if(outputFiles.is_open())
{
for(int i=0; i<=s.numberOfNames; i++)
{
outputFiles << s.studentNames [i] << "\n";
}
}
}
Upvotes: 0
Views: 684
Reputation: 41301
Change
for (int i=0; i<=numberOfNames; i++)
to
for (int i=0; i < numberOfNames; i++)
everywhere in your program.
Upvotes: 1