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

65 Views Asked by At

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;
2

There are 2 best solutions below

0
Remy Lebeau On BEST ANSWER

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

0
Chris On

As noted in comments, iomanip settings need to be applied before the item they are meant to apply to.

Filling in values for the missing variables from your example:

#include <iomanip>
#include <iostream>

int main() {
  std::cout << "Foo " << "[" 
            << std::setfill(' ') << std::setw(15)
            << "Bar" << "] " 
            << std::fixed << std::setprecision(2) <<  20.897
            << " " << 1.4566 << std::endl;

  return 0;
}

Output:

Foo [            Bar] 20.90 1.46