c ++将int转换为char +将前导零添加到char

Sem*_*exB -5 c++ type-conversion leading-zero

我从0到999得到了数字.我怎样才能实现以下目标

int i = 123;//possible values 0-999
char i_char[3] = /*do conversion of int i to char and add 3 leading zeros*/
Run Code Online (Sandbox Code Playgroud)

示例:i_char看起来像是"001"for i=1,"011"for i=11"101"fori=101

Che*_*Alf 5

使用std::ostringstreamwith std::setfill()std::setw(),例如:

#include <string>
#include <sstream>
#include <iomanip>

int i = ...;
std::ostringstream oss;
oss << std::setfill('0') << std::setw(3) << i;
std::string s = oss.str();
Run Code Online (Sandbox Code Playgroud)