0

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.

3
  • 1
    Use std::string and std::vector<std::string> instead of a dynamically allocated array of char* Commented Nov 3, 2014 at 19:55
  • If getline fails then your buffers will all be full of garbage which could cause the problem Commented Nov 3, 2014 at 20:57
  • @MattMcNabb I think it may be the getline that causes the bug. I have declared namesSet as char namesSet[100] Commented Nov 3, 2014 at 22:19

1 Answer 1

1

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++)
Sign up to request clarification or add additional context in comments.

5 Comments

+1. Writing past the end of the buffer could definitely account for it.
I just tried that... doesn't make a difference. Like I mentioned, I think its the output file stream
@user4167396: This is a bug nonetheless, leading to undefined behavior. You may have other bugs as well.
@user4167396: If fixing this bug didn't solve the problem, I think you have errors in code you haven't shown. For example, I'm suspicious of sizeof(namesSet), since sizeof on a pointer is a common bug. But you haven't shown the declaration of namesSet.
@FredLarson namesSet is declared as char namesSet[100]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.