C ++将int转换为char +将前导零添加到char
c++ converting int to char + add leading zeros to char
我得到了从 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
对于 i=1
应类似于 "001"
,对于 i=11
应类似于 "011"
,对于 [=] 应类似于 "101"
17=]
使用 std::ostringstream
与 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();
您似乎在寻找 sprintf,或者 printf。
int i = 123;
char str[10];
sprintf(str, "%03d", i);
因为您用 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;
}
对于 i=1
它将输出:001
.
我得到了从 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
对于 i=1
应类似于 "001"
,对于 i=11
应类似于 "011"
,对于 [=] 应类似于 "101"
17=]
使用 std::ostringstream
与 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();
您似乎在寻找 sprintf,或者 printf。
int i = 123;
char str[10];
sprintf(str, "%03d", i);
因为您用 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;
}
对于 i=1
它将输出:001
.