简体   繁体   中英

How to format output using cout

I am aware that it is likely possible to do this using some other method such as printf(), but I want to know if this can be done using cout.

Insert -8:   -8 90 34 -78 34 235 9 -12 653
Insert -78:  -78 -8 34 90 34 235 9 -12 653

This is partial output from a sorting algorithm. It is showing what happens after each pass. Each number is from the same vector. How is it possible to have the minus signs always align for the first element as shown above (elements after that don't matter)?

Currently my code looks like this:

cout << "Insert " << my_vector[pos] << ": ";

for (int k = 0; k < size_of_vector; k++) {
  cout << my_vector[k] << " ";
}

cout << endl;

However, my code results in output that looks like this:

Insert -8: -8 90 34 -78 34 235 9 -12 653 
Insert -78: -78 -8 34 90 34 235 9 -12 653 

A simple way is to output the lead-in as a single string, in a specified field width, eg

cout
    << "Insert "
    << setw( 14 ) << to_string( my_vector[pos] ) + ":";

The magic number needs to be chosen to accomodate the maximum number of digits and sign.

Disclaimer: code not touched by compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM