Search code examples
c++ofstream

Why is my first ofstream output in my else block missing the fill character?


I'm using this code to output nodes of a huffman tree to a text file with a certain formatting. All the node outputs within the if block run as expected, but the first output in the else block is missing the '0' fill character after the "L:". It should output "L:076" but instead is outputting "L: 76". The cout looks correct but the text file isn't. All future loops through the else block output like they should, it's only the first loop that is missing the fill character. Here's a picture of my output enter image description here

void preOrder(node* tree, std::ofstream& of) {
    if (tree->label > 0) {
        of << "I:" << tree->label << " ";
    }
    else {
        std::cout.width(3);
        std::cout << std::right;
        std::cout.fill('0');
        std::cout << int(tree->ch) << std::endl;
        of << "L:";
        of << of.fill('0');
        of << std::right;
        of << int(tree->ch);
        of << " ";
        return;
    }
    preOrder(tree->left, of);
    preOrder(tree->right, of);
}

Solution

  • From cppreference.com:

    The second form (2) sets fillch as the new fill character and returns the fill character used before the call.

    "The second form" is the non-const version, that applies here. So my guess (I never used fill myself and I cannot compile your code as it is) would be that the call is correctly applied and then you put the old fill character (blank space presumably) to the stream, because you do:

    of << of.fill('0');
    

    Also, I noticed that you dont set the width of of.