Search code examples
c++visual-studio-2013text-alignmentiomanip

Alignment problems with <iomanip>


So I'm using the iomanip library to cout this:

std::cout << std::endl
    << std::left << std::setw(15) << "Ticker Symbol"
    << std::setw(100) << "Stock Name"
    << std::setw(12) << "Value"
    << std::setw(10) << "Date"
    << std::setw(10) << "YTD Return"
    << std::endl;

The problem is that it ends up printing this:

T       icker SymbolS                       tock NameV      alueD       ateY    TD Return

Instead of:

Ticker Symbol    Stock Name                            Value    Date    YTD Return

Is there a way I can fix this without using another library?

Edit: My Operator overloading function appears to be causing this issue:

std::ostream& operator<< (std::ostream& out, const char array[])
{
    for (uint8_t i = 0; array[i] != '\0'; i++)
    {
        out << array[i];
    }
    return out;
}

That being said, I still don't know how to fix this issue.


Solution

  • Why do you have to overload the operator? That is certainly what is causing your problem.

    setw will get applied to the first thing output to the stream, and because you have c-strings output one letter at a time, the setw gets applied to only the first letter - producing the behavior you are seeing.

    The easiest thing to do is get rid of your operator overload. Otherwise you need to get the width from cout.width(), output one letter at a time, then add in the extra spaces afterward:

    std::ostream& operator<< (std::ostream& out, const char array[])
    {
        int width = out.width();
        out.width(0);
        int array_size = 0;
        for (uint8_t i = 0; array[i] != '\0'; i++, array_size++)
        {
            out << array[i];
        }
    
        for (int i = array_size; i < width; i++)
        {
            out << " ";
        }
    
        return out;
    }