user2079828
user2079828

Reputation: 655

Bad characters in file output

Writing a preorder traversal of a optimal binary search tree to a .txt file recursively. The code is:

 void PrintTree(int i, int j, int space)
{
    if(i < j)
    {
        outfile.write("", space++);
        outfile<<A[Rt[i][j]]<<endl;
         PrintTree(i, Rt[i][j], space);
         PrintTree(Rt[i][j] + 1, j, space);
    }
    else
    {
        outfile.write("",space);  //This line
         outfile.write("-\n",2);      
    }
}

This output works for small trees, like up to 7-10. More than that gives me bad some bad characters, and I can't seem to find where they are coming from.

F

 A

  -

  C

   B

    -

    -

   E

    D

    Ì-

    Ì-

    -

 K

  I

   H

    G

    Ì-

    Ì-

    -

   J

    -

    -

  M

   L

    -

    -

   O

    N

    Ì-

    Ì-

    -

Is an example of the output I am getting. I have no idea what the 'Ì' characters are from in that code.

const int n = 15;
char A[n] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',  'O'};
int P[n] = {150, 25, 50, 25, 50, 125, 25, 75, 75, 50, 150, 75, 50, 25, 50};

 int S[n+1][n+1] = {};
 int Rt[n+1][n+1] = {};

These are all my initial arrays.(above)

 PrintTree(0, n, 0);

Is my initial call to print tree. S[][] is the array in the file I linked in comments...it is the numbers. Rt[][] contains numbers corresponding to A[n]. So, Rt[i][j] = 1; maps to A[1] which is 'B'.

The arrays themselves are not being accessed out of bounds, and it only happens when 'space' becomes 4 or greater, so that would be 4 levels deep into the recursion.

Upvotes: 2

Views: 1383

Answers (1)

msnider
msnider

Reputation: 444

This is almost certainly a problem with the way you are tracking your recursion depth.

outfile.write("",space);

Here you are telling the write() function to print space characters of the empty string "". Up to a certain level, this appears to work fine (e.g. the Ì always occurs at a depth of 5 for the output you supplied).

If you look it up, ostream& write (const char* s, streamsize n) is meant to have as its first argument an array of at least n characters, and its second argument is the number of characters to write. Instead you should do something like this:

outfile << std::string(spaces, ' ') << '-' << std::endl;

Which will create and write a new string of whitespace with length spaces to the outfile stream.

Upvotes: 2

Related Questions