-3

我得到了从 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

4

3 回答 3

5

将 astd::ostringstreamstd::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();
于 2016-07-19T14:57:23.483 回答
2

看来您正在寻找 sprintf,或者可能是 printf。

int i = 123;
char str[10];
sprintf(str, "%03d", i);
于 2016-07-19T15:01:17.260 回答
0

因为,您在此处标记了问题,c++这是使用std::stringand的快速解决方案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.

于 2016-07-19T15:05:09.843 回答