Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

output void function to txt

Tags:

c++

iostream

I am only in my second quarter of c++ so please keep answers simple....

I have a pretty messy program with linklist, class, and file i/o I am pretty much done with the program but I cant get it to output to a .txt It might have been my bad coding layout, since outputting slipped my mind when I wrote this. the function in question is:

tag.display_balance(); 

note that this function is inside a linklist (tag) that goes into a class and call the function (display_balance) to print the outputs.

everything comes out to the console just fine. but I dont know how to get it save onto a .txt a few Google and forum searches didnt show anything that I can understand. I tried:

ofstream BilloutPut;
BilloutPut.open("BillingStatements.txt");
BilloutPut<< tag.display_balance(); 

which is the only way I have learned how to output to a file, but since it is a void function it didnt work. I would like to keep away from overloading the << function if possible.

-Thanks for looking

like image 606
kingcong3 Avatar asked Mar 22 '26 17:03

kingcong3


1 Answers

If the function does its own file I/O, it's going to be tough (that's why the "separation of concerns" software design guideline exists, it's apparently being violated here). Overloading operator << will not help, there's no return value from the function for such an operator to put anywhere.

If you can modify the function, have it accept an argument which is the ostream object to write to (this can default to cout).

If you can't modify the function, but it uses std::cout, you can use cout.rdbuf(newbuffer) to redirect std::cout by associating it with another destination.

If the function uses some other I/O library, you may have to use freopen or even dup2 to remap stdout (the OS standard output file descriptor) to another destination.

And beware, any of the techniques involving redirection (i.e. cout.rdbuf, freopen, and dup2) will make a huge mess in any multithreaded program. This probably doesn't apply to you as a beginning programmer, but when you start with threading you need to design your I/O functions to use whatever stream you want, global solutions just won't cut it.

like image 109
Ben Voigt Avatar answered Mar 25 '26 07:03

Ben Voigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!