I'm trying to write console data into a separate text file in cpp. Anybody help me with sample code.
There are various ways to do this. You could redirect it from the command line with programname > out.txt
. Or you could use freopen("out.txt","w",stdout);
at the start of your program.
If you want to write from your own process, I'd suggest a simple print method
void print(const string str, ostream & output)
{
output << str;
}
Then you can call
print("Print this", cout);
for console output, or
ofstream filestream("filename.out");
print("Print this", filestream);
to write into a file "filename.out". Of course you gain most, if print
is a class method that outputs all the object's specific information you need and this way you can direct the output easily to different streams.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With