Search code examples
c++type-conversionleading-zero

c++ converting int to char + add leading zeros to char


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


Solution

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

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