Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading