简体   繁体   中英

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

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

// Assume x is in the correct range (0 <= x <= 9999)
char target[5];
sprintf(target, "%04d", x);

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; 
  }

Try

char y[5];
sprintf(y, "%4d", x);

What is the logical role of the number? Normally, you'd define a manipulator whose name is based on the logical role, and use it. Maybe somthing like:

class serialno
{
    int myWidth;
public:
    serialno( int width ) : myWidth( width ) {}
    friend std::ostream& operator<<(
        std::ostream& stream, serialno const& manip )
    {
        stream.fill( '0' );
        stream.width( myWidth );
        return stream;
    }
};

You can then write:

std::cout << serialno( 4 ) << myNumber;

(A better implementation would save the formatting state of the stream, and restore it in the destructor, called at the end of the full expression.)

To put this into a character array, of course, you use an std::ostringstream rather than std::cout .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM