简体   繁体   English

使用setw和setfill进行输出格式化

[英]Output formatting using setw and setfill

I'm trying to get the following output using setw and setfill: 我正在尝试使用setw和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. std::setw是用于以表格格式打印长度可变的数据的出色工具。 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 << " " . 但是,如果您需要固定数量的空格, cout << " "容易对其进行硬编码: 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. 这使您可以在以后根据需要轻松调整缩进量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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