简体   繁体   中英

Output formatting using setw and setfill

I'm trying to get the following output using setw and setfill:

OPTIONS:
    <expression>
       The usual operators +, -, *, / and % (remainder)
       Expressions are fixed-point decimal numbers, and
       Parentheses () and corchetes {} may be used for grouping.

I'm trying like this:

    cout << "OPTIONS:" << '\n';
    cout << "\t<expression>\n";
    cout << '\t' << setw(3) << setfill(' ') << "The usual operators +, -, *, / and % (remainder)\n";
    cout << '\t' << setw(3) << setfill(' ') << "Expressions are fixed-point decimal numbers, and\n";
    cout << '\t' << setw(3) << setfill(' ') << "Parentheses () and corchetes {} may be used for grouping.\n\n";

std::setw is a great tool for printing data with varying length in a table format. You specify the width of a column and spaces will get filled in automatically until the specified column width is reached. However, if you need a fixed number of spaces it's easier to hard code them: cout << " " . If you need the same indentation many times you might want to define this as a constant

auto indent = string(3, ' ');
cout << indent << ...;

This allows you to easily adjust the indentation later if needed.

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