c++iomanip

How to guarantee that std::cout always uses n width


I have output that looks like this:

BTC-USDT              [FTX] 20460.91 20470.09
BTC-USDT              [BINANCE_US] 20457.34 20467.28 
BTC-USDT              [BINANCE_US] 20457.50 20467.28

I would like it to look like this:

BTC-USDT  [       FTX] 20460.91 20470.09 
BTC-USDT  [BINANCE_US] 20457.34 20467.28
BTC-USDT  [BINANCE_US] 20457.50 20467.28

I think I am close with this code, but I am confused by setw()

std::cout << pair << std::setfill(' ') << std::setw(15) << " [" << exch << "] " << fixed << setprecision(2) <<  bid << " " << ask << std::endl;

Solution

  • If you want a given value to have certain output characteristics, like width, alignment, etc, you need to apply the appropriate I/O manipulator(s) before you output the value, not after.

    In your example, you want pair to be left-aligned with a width of 9, and exch to be right-aligned with a with of 10, so apply std::setw and std::left/std::right accordingly, eg:

    std::cout << std::setfill(' ')
              << std::setw(9) << std::left << pair
              << " [" << std::setw(10) << std::right << exch << "] "
              << std::fixed << std::setprecision(2) << bid << ' ' << ask
              << std::endl;
    

    Output:

    BTC-USDT  [       FTX] 20460.91 20470.09
    BTC-USDT  [BINANCE_US] 20457.34 20467.28
    BTC-USDT  [BINANCE_US] 20457.50 20467.28
    

    Online Demo