简体   繁体   中英

formatted output of a number and field width, where does the C++ standard say about it?

This code snippet:

//
// This is example code from Chapter 11.2.5 "Fields" of
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    cout << 123456                        // no field used
         <<'|'<< setw(4) << 123456 << '|' // 123456 doesn't fit in a 4 char field
         << setw(8) << 123456 << '|'      // set field width to 8
         << 123456 << "|\n";              // field sizes don't stick
}

produces this output:

123456|123456|  123456|123456|

The second print of 123456 is not truncated to fit in a field with width of 4 and Stroustrup explains that it is the right thing to do because a bad looking table with right numbers is better than a good looking table with wrong numbers.

where does the C++ standard say about this behaviour?

I found ios_base::width where the standard says:

The minimum field width (number of characters) to generate on certain output conversions

Is "minimum" the keyword here to explain the said behaviour?

The statement you cite is a generic description. Regardless of what is being output, the field will have at least that many characters; that is the meaning of minimum . The exact meaning of the field depends on the type of data being output. In the case of integer output, the exact format is specified in §22.4.2.2; this includes not only how the width field is interpreted, and a guarantee that the field will not be larger unless necessary to display the value according to the format specified, but also what character to use for the fill, and where to put it. (Stroustrup's example leaves all of the other parameters with their default values, but if you have a negative number, and specified a fill character of '0', you wouldn't want it to result in |000-1234| , but rather |-0001234| .)

For user defined types, it's entirely possible that the field contain less than the minimum. I would consider this a bug, but I imagine a lot of user defined << are written without consideration of any of the formatting parameters. The actual effect of std::setw is only to set a field in the std::basic_ios<char> class; it's up to the implementation of << to handle it correctly.

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