C++ Program not inserting text to file

I have a program that is supposed to insert text to a text file, but it is not inserting the desired text
Heres the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;

int main() {

    ofstream f("dataa.txt");
    f.open ("dataa.txt", ofstream::out | ofstream::app);
    f << "Some random text";
    f.close();
    
}
Last edited on
Line 9 line opens the stream and truncates the file to zero size.
Line 10 attempts to open the stream, this time with the proper flags. Unfortunately, the stream is already open, so the operation fails.

Remove line 10 and add ofstream::out | ofstream::app to line 9:
std::ofstream f ("dataa.txt", ofstream::out | ofstream::app);

You usually shouldn't bother to explicitly close the file. It will be closed automatically when the stream is destroyed.
Last edited on
Thanks,
Really helped
Topic archived. No new replies allowed.