Reputation: 29
I am trying to write a program that takes a list of names and then outputs it to a .txt
file.
This is my code:
void setNames() // Set method that takes a series of names.
{
nameTags = new char*[numberOfNames];
for (int i=0; i<=numberOfNames; i++)
{
nameTags[i] = new char[128];
cout << "Input information for name " << i << ": " << "\n";
cin.getline(namesSet, sizeof(namesSet));
strcpy(nameTags[i], namesSet);
}
}
ostream& operator<< (ostream& ostr, const Names& names) // <<operator
{
ostr << "#############################" << endl;
ostr << names.getAuthor();
ostr << names.getNumberOfNames();
for(int i=0; i<=names.numberOfNames; i++)
{
ostr << names.nameTags [i] << "\n";
}
return ostr;
}
Now my program works fine and prints to a terminal. However, when I try running this after the ofstream
it crashes and is not very good. For example, if I want to input 10 names, and save it to disk it crashes.
ofstream outputfile (names.getFileName());
if(outputfile.is_open())
{
outputfile << names; // I believe I go wrong here.
outputfile.close();
}
I am new to C++ and I would greatly appreciate it if someone could help me out with my problem. I have been spending hours trying to fix it.
Upvotes: 0
Views: 1267
Reputation: 779
The problem is with statement:
for (int i=0; i<=numberOfNames; i++)
Instead it should be
for (int i=0; i < numberOfNames; i++)
Also in the stream insertion operator it should be:
for(int i=0; i < names.numberOfNames; i++)
Upvotes: 1