Search code examples
c++ostreamsetw

C++ ostream fill adding a trailing 0


Hello I am having an issue formatting my output using the ostream object in C++.

ostream& write(ostream& os)
{
    os << os.fill('*') << os.width(10);
    return os;
}

This is what the output looks like:

********* 0

I'm trying to achieve 10 *s without the trailing 0.

What is the cause of the trailing 0?

Am I using width and fill functions incorrectly?


Solution

  • As it says in ios::base::width :

    Return value : The value of the field width before the call.

    So what you are doing is fill your ostream with *s and then print the value of the field before call which is 0.

    And there is another thing that you probably didn't notice that before 0, you have another char, that's because of std::ios::fill return value :

    Return value : The value of the fill character before the call.

    Try this :

    ostream& write(ostream& os)
    {
        os.fill('*');
        os.width(10);
        return os;
    }