How do I use a manipulator to format my hex output with padded left zeros
-
23-09-2019 - |
Question
The little test program below prints out:
And SS Number IS =3039
I would like the number to print out with padded left zeros such that the total length is 8. So:
And SS Number IS =00003039 (notice the extra zeros left padded)
And I would like to know how to do this using manipulators and a stringstream as shown below. Thanks!
The test program:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
int i = 12345;
std::stringstream lTransport;
lTransport << "And SS Number IS =" << std::hex << i << '\n';
std::cout << lTransport.str();
}
Solution
Have you looked at the library's setfill and setw manipulators?
#include <iomanip>
...
lTransport << "And SS Number IS =" << std::hex << std::setw(8) ;
lTransport << std::setfill('0') << i << '\n';
The output I get is:
And SS Number IS =00003039
OTHER TIPS
I would use:
cout << std::hex << std::setw(sizeof(i)*2) << std::setfill('0') << i << std::endl;
You can use setw and setfill functions as follows:
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
int main()
{
int i = 12345;
std::stringstream lTransport;
lTransport << "And SS Number IS =" << setfill ('0') << setw (8)<< std::hex << i << '\n';
std::cout << lTransport.str(); // prints And SS Number IS =00003039
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow