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

时间:2016-07-19 14:55:22

标签: 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*/

示例:i_char "001"的{​​{1}},i=1的{​​{1}}或"011"的{​​{1}}。 }

3 个答案:

答案 0 :(得分:5)

std::ostringstreamstd::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();

答案 1 :(得分:1)

看来你正在寻找sprintf,或者也许是printf。

int i = 123;
char str[10];
sprintf(str, "%03d", i);

答案 2 :(得分:0)

因为,您使用ListB.Select(y => y.v)标记了问题,这是使用update table2 t2 join table1 t1 on t2.Name = t1.Name set t2.Lollipops = t1.Chocolates + 1 c++的快速解决方案:

std::string

对于std::to_string,它会输出:#include <iostream> #include <string> int main() { int i = 1; std::string s = std::to_string(i); if ( s.size() < 3 ) s = std::string(3 - s.size(), '0') + s; std::cout << s << std::endl; return 0; }