开发者

output void function to txt

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:

ta开发者_运维技巧g.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


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.


Thanks for the replies, I think im going to modify the function, but im not sure how to work with ostream.

void linkD::display_balance(){

ListNode *nodePtr;
nodePtr = head;

while (nodePtr){
    nodePtr->driver.print_balanceReport();
    cout<<endl;
nodePtr = nodePtr->next;
}


void driver::print_balanceReport(){
    nBalance=balance;
    cout<<get_firstName()<<" ";
    cout<<get_lastName()<<" ";
    cout<<get_dLicense()<<" ";
    cout<<get_vLicense()<<" ";
    cout<<get_nBalance()<<" ";
    cout<<get_passed()<<" ";
    cout<<get_differance()<<" ";}

print from the class (driver)

so would i change the void into ostream and treat it like a function type?? also just for my knowledge can I traverse my linkedlist from the main, so that i skip the function??

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜