I am writing a C++ code in which I have dynamically created an array of strings. I have written functions to output both the number of items in the string array as well as the array itself. The next thing I wanted to do is stored the elements of the array in a text file, but when I open the file I have written to, only the last element of the array shows up. Here is a sample of what I am doing:
int num_elem = ReadNumElem(); // my function that gets the number of elements in the array of strings
string *MyStringArray = ReadNames(num_elem); // my function that reads a file and outputs the necessary strings into the array
for(int i = 0; i < num_elem < ++i) {
ofstream ofs("C:\\Test\\MyStrings.txt")
ofs << MyStringArray[i] << endl; // I also tried replacing endl with a "\n"
}
I am new to C++, so I apologize if this is too simple, but I have been searching for some time now, and I can't seem to find a solution. The first two functions are not relevant, I only need to know how to output the data into a text file so that all the data shows up, not just the final element in the array. Thanks!
std::ios_base::appas a flag in yourmodeargument to theofstreamconstructor, e.g.std::ofstream ofs("C:\\Test\\MyStrings.txt", std::ios_base::out | std::ios_base::app);