C++标准模板(STL)- 输入/输出操纵符-(std::setprecision,std::setw)

操纵符是令代码能以 operator<< 或 operator>> 控制输入/输出流的帮助函数。

不以参数调用的操纵符(例如 std::cout << std::boolalpha; 或 std::cin >> std::hex; )实现为接受到流的引用为其唯一参数的函数。 basic_ostream::operator<< 和 basic_istream::operator>> 的特别重载版本接受指向这些函数的指针。这些函数(或函数模板的实例化)是标准库中仅有的可取址函数。 (C++20 起)

以参数调用的操纵符(例如 std::cout << std::setw(10); )实现为返回未指定类型对象的函数。这些操纵符定义其自身的进行请求操作的 operator<< 或 operator>> 。

定义于头文件 <iomanip>
 

更改浮点精度

std::setprecision

定义于头文件 <iomanip>

/*unspecified*/ setprecision( int n );

用于表达式 out << setprecision(n) 或 in >> setprecision(n) 时,设置流 outinprecision 参数准确为 n

参数

n - 精度的新值

返回值

返回未指定类型的对象,使得若 str 是 std::basic_ostream<CharT, Traits> 类型的输出流名称或 std::basic_istream<CharT, Traits> 类型的输入流名称,则表达式 str << setprecision(n) 或 str >> setprecision(n) 表现为如同执行下列代码:

str.precision(n);

调用示例

#include <iostream>
#include <iomanip>
#include <cmath>
#include <limits>

int main()
{
    const long double pi = std::acos(-1.L);
    std::cout << "default precision (6): "
              << pi << std::endl
              << "std::setprecision(10): "
              << std::setprecision(10) << pi << std::endl
              << "max precision:         "
              << std::setprecision(std::numeric_limits<long double>::digits10 + 1)
              << pi << std::endl;

    return 0;
}

输出

更改下个输入/输出域的宽度

std::setw

/*unspecified*/ setw( int n );

 用于表达式 out << setw(n) 或 in >> setw(n) 时,设置流 outinwidth 参数准确为 n

参数

n - width 的新值

返回值

返回未指定类型对象,满足若 str 是 std::basic_ostream<CharT, Traits> 或 std::basic_istream<CharT, Traits> 类型流的名称,则表达式 str << setw(n) 或 str >> setw(n) 表现为如同执行下列代码:

str.width(n);

注意

若调用任何下列函数,则流的宽度属性将被设为零(表示“不指定”):

  • 输入
  • operator>>(basic_istream&, basic_string&)
  • operator>>(basic_istream&, char*)
  • 输出
  • basic_ostream::operator<<() 的重载 1-7 (在 num_put::put() 的阶段 3 )
  • operator<<(basic_ostream&, char) 和 operator<<(basic_ostream&, char*)
  • operator<<(basic_ostream&, basic_string&)
  • std::put_money (在 money_put::put() 内)
  • std::quoted (以输出流使用时)

此修改器在输入与输出上的准确效果在单独的 I/O 函数间有别,单独地描述于每个 operator<<operator>> 重载的页面。

调用示例

#include <sstream>
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << "no setw:" << 42 << std::endl
              << "setw(6):" << std::setw(6) << 42 << std::endl
              << "setw(6), several elements: " << 89
              << std::setw(6) << 12 << 34 << std::endl;

    std::istringstream is("hello, world");
    char arr[10];
    is >> std::setw(6) >> arr;
    std::cout << "Input from \"" << is.str()
              << "\" with setw(6) gave \""
              << arr << "\"" << std::endl;

    return 0;
}

输出

猜你喜欢

转载自blog.csdn.net/qq_40788199/article/details/133419821