Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an integer to a fixed-length character array in C++

Tags:

c++

arrays

char

int

I have an integer x that contains a 1-4 digit number. How can I convert it to a 4-character array of the digits (padded with zeroes if necessary)? That is, if x is 4, I want character array y to contain 0004

like image 959
user1165574 Avatar asked Feb 22 '23 15:02

user1165574


2 Answers

// Assume x is in the correct range (0 <= x <= 9999)
char target[5];
sprintf(target, "%04d", x);
like image 73
Asaf Avatar answered Mar 02 '23 00:03

Asaf


Well, if you are guaranteed to have only 4 elements in the vector, I think you will be able to do with with the following:

  char result[4];
  for(int i=0;i<4;++i)
  {
    result[3-i] = (value % 10);
    value /= 10; 
  }
like image 40
Craig H Avatar answered Mar 01 '23 23:03

Craig H