Stephen Lutz
Stephen Lutz

Reputation: 1

Array of Strings to Output File

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!

Upvotes: 0

Views: 4104

Answers (2)

Rocky Pulley
Rocky Pulley

Reputation: 23301

You are opening the file every time in the array and overwriting its contents.

Try:

ofstream ofs("C:\\Test\\MyStrings.txt");    
for(int i = 0; i < num_elem ; ++i) {
            
    ofs << MyStringArray[i] << endl; // I also tried replacing endl with a "\n"
}
ofs.close();

Upvotes: 3

Bowler
Bowler

Reputation: 411

You need to declare the file outside of the loop

edit


Sorry I didn't mean to answer in one line but it has been done now anyway.

Upvotes: 1

Related Questions