-3

I have coded a programm which can load one text file, can decide how long each word is and can write txt files based on the length of the words. But when i run the programm, the new text files are always filled with just one word(each new word with an already existing text file for his length just overrides the text file)

The start text file looks like this():

https://i.stack.imgur.com/WBaRf.png

My new created text files(named after their length for example: 7.txt) after i runned the programm:

https://i.stack.imgur.com/6QKgE.png

My code:

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

int main(int argc, char *argv[])
{
    char     filename[128];
    ifstream file;
    char     line[100];

cout << "Input filename: " << flush;
cin.getline(filename, 127);

file.open(filename, ios::in);

if (file.good())
{
    file.seekg(0L, ios::beg);
    int number = 0;
    while (!file.eof())
    {
        file.getline(line, 100);
        stringstream stream;
        stream << line;
        number++;
        cout <<"Number: "<< number << " length: " << stream.str().length() << " " << line << endl;
        std::stringstream sstm;
        int laenge = stream.str().length();
        string txt = ".txt";
        sstm << laenge << txt;
        string result = sstm.str();
        std::ofstream outFile(result);
        outFile << line << endl;
        outFile.close();
    }
}
else
{
    cout << "File not found" << endl;
}

while (true)
{
};

return 0;

}

My goal is that i have sorted the whole words into the file their files, the only problem is that they overwrite themself... How can i get rid off that?

Jordan Zapf
  • 65
  • 1
  • 11

1 Answers1

0

If you don't want to overwrite the content of the file, you can open the file and specify that you want to append to the file:

std::ofstream outFile(result, ios::app);
                           // ^^^^^^^^
Andreas DM
  • 10,685
  • 6
  • 35
  • 62