-3

I got numbers from 0 to 999. How can I achieve the following

int i = 123;//possible values 0-999
char i_char[3] = /*do conversion of int i to char and add 3 leading zeros*/

Example(s): i_char shall look like "001" for i=1, "011" for i=11 or "101" for i=101

SemtexB
  • 660
  • 6
  • 21

3 Answers3

5

Use a std::ostringstream with std::setfill() and std::setw(), eg:

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

int i = ...;
std::ostringstream oss;
oss << std::setfill('0') << std::setw(3) << i;
std::string s = oss.str();
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
2

It appears you are looking for sprintf, or perhaps printf.

int i = 123;
char str[10];
sprintf(str, "%03d", i);
Sven Nilsson
  • 1,861
  • 10
  • 11
0

Since, you tagged the question with c++ here is a quick solution using 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;
}

For i=1 it will output: 001.

DimChtz
  • 4,043
  • 2
  • 21
  • 39