c++ - setf(ios::left, ios::adjustfield) 的组合有什么作用?

标签 c++ stl

我在读一本教科书时遇到了这条线。

它似乎在两列中漂亮地格式化输出(我猜左边的设置宽度使右边的看起来即使它都从同一列开始)。不过,我不太确定这条线到底在做什么。

cout.setf(ios::left, ios::adjustfield);

有人能给我解释一下吗?

最佳答案

它强制以左对齐方式输出固定宽度字段中的文本。参见 this reference .这是使用该函数的第二个覆盖,该函数接受用于设置特定标志的掩码。

此覆盖将清除 std::ios_base::adjustfield 中设置的任何现有标志,它通过 stream 对象处理文本输出的对齐。

不采用标志掩码(第二个参数)的覆盖将简单地另外设置指定的标志,这在 adjustfield 的情况下没有多大意义,因为有效值只有 leftrightinternal,它们都处理文本对齐。

希望这个小例子能说明问题:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
   cout.setf(std::ios::left, std::ios::adjustfield);
   cout << setfill('^') << setw(10) << "Hello" << "\n";

   cout.setf(std::ios::right, std::ios::adjustfield);
   cout << setfill('0') << setw(10) << "99\n";

   return 0;
}

它给出了输出:

Hello^^^^^
000000099

关于c++ - setf(ios::left, ios::adjustfield) 的组合有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8344118/

相关文章:

c++ - 使用 std::thread 在 C++ 中进行线程化

c++ - 对 cblas_sgemm 的 undefined reference

c++ - lua 5.2.1 Unresolved external 问题

c++ - friend 声明的放置

c++ - 如何在 C++ 中为 copy_if 等定义 "unary predicate"?

c++ - 将 std::unique_ptr 移动到 std::vector 内的新位置

C++按值获取数组元素的索引

c++ - 在对 float : expression must have integral or unscoped enum type 执行平方和平方根时

c++ - C++ 中的两个键映射

c++ - 为什么 std::fstream 类不采用 std::string?