Fra*_*ank 54 c++ formatting numbers
如何在C++中格式化输出?换句话说,什么是C++相当于使用printf这样的:
printf("%05d", zipCode);
Run Code Online (Sandbox Code Playgroud)
我知道我可以printf在C++中使用,但我更喜欢输出运算符<<.
你会使用以下内容吗?
std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;
Run Code Online (Sandbox Code Playgroud)
pax*_*blo 83
这样就可以了:
#include <iostream>
#include <iomanip>
using namespace std;
cout << setw(5) << setfill('0') << zipCode << endl;
// or use this if you don't like 'using namespace std;'
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
Run Code Online (Sandbox Code Playgroud)
控制填充的最常见IO操纵器是:
std::setw(width) 设置字段的宽度.std::setfill(fillchar) 设置填充字符.std::setiosflags(align) 设置对齐,其中align是ios :: left或ios :: right.使用setw和setfill调用:
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
Run Code Online (Sandbox Code Playgroud)
cout << setw(4) << setfill('0') << n << endl;
Run Code Online (Sandbox Code Playgroud)
从:
http://www.fredosaurus.com/notes-cpp/io/omanipulators.html
在 C++20 中,您将能够执行以下操作:
std::cout << std::format("{:05}", zipCode);
Run Code Online (Sandbox Code Playgroud)
在此期间,您可以使用的{} FMT库,std::format是基于。
免责声明:我是 {fmt} 和 C++20 的作者std::format。