我得到了从 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"
for i=1
,"011"
fori=11
或"101"
fori=101
我得到了从 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"
for i=1
,"011"
fori=11
或"101"
fori=101
将 astd::ostringstream
与std::setfill()
and一起使用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();
看来您正在寻找 sprintf,或者可能是 printf。
int i = 123;
char str[10];
sprintf(str, "%03d", i);
因为,您在此处标记了问题,c++
这是使用std::string
and的快速解决方案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;
}
因为i=1
它将输出:001
.