DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Incorrect output file: c++ (i/o) question (http://www.daniweb.com/forums/thread159275.html)

drjay1627 Nov 24th, 2008 2:48 pm
Incorrect output file: c++ (i/o) question
 
I encode a text file using a huffman tree. Which print out to the screen and and output to a file. File only contains the last line that prints to the console.

void traverse(string code = "") const {
                string outputFile = "huffman.txt";
                ofstream outfile(outputFile.c_str());


                if (child0 !=NULL) {

                        static_cast<huffman_item<dtype> >( *child0).traverse(code + '0' );               

                        static_cast<huffman_item<dtype> >( *child1).traverse(code + '1' );

                } else{

                        outfile << data << freq << code << endl;
                        cout << " Data: " << data << " Frequency: " << freq << " Code: " << code << endl;

                }

        }

This is method. Can someone please help me!

skatamatic Nov 24th, 2008 2:55 pm
Re: Incorrect output file: c++ (i/o) question
 
Is recursion really necessary for this? Whenever possible avoid using it. It's inefficient, hard to implement, and hard to debug. It seems as though the function recursively calls itself until it is at the end of the list, then it displays a line. In each recursive call, you should be outputting a line, otherwise it will traverse to the end and display the last line. If recursion isn't necessary, use a loop instead.

drjay1627 Nov 24th, 2008 2:59 pm
Re: Incorrect output file: c++ (i/o) question
 
figure out the problem! this is a recursive function...

drjay1627 Nov 24th, 2008 3:00 pm
Re: Incorrect output file: c++ (i/o) question
 
yeah it creates a output file each time the function is called. the way i have it setup i need a recursive function.

skatamatic Nov 24th, 2008 3:01 pm
Re: Incorrect output file: c++ (i/o) question
 
Quote:

Originally Posted by drjay1627 (Post 743667)
figure out the problem! this is a recursive function...

Ummm...ok? I'm pretty sure I told you the solution. Being polite will get you farther in life.

drjay1627 Nov 24th, 2008 3:03 pm
Re: Incorrect output file: c++ (i/o) question
 
I replied the before I read you solution. Didn't expect a quick response. Sorry mate!

I still have the same problem though! Need to figure out a way to edit an existing file rather than create a new file. Or maybe I should create a file before the function is called...

skatamatic Nov 24th, 2008 3:14 pm
Re: Incorrect output file: c++ (i/o) question
 
Open the file in append mode.

ostream fOut;
fOut.open("file.dat", ios::append);

I'm pretty sure that's how it's done.


All times are GMT -4. The time now is 7:58 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC