LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to format int 1 to string 0001 in C++? (https://www.linuxquestions.org/questions/programming-9/how-to-format-int-1-to-string-0001-in-c-862985/)

chinho 02-16-2011 01:21 AM

How to format int 1 to string 0001 in C++?
 
Hi guys,

In C++ as subjected, can anyone throw me some light on how I can generic-ly format an integer value of 1 to a string value of 0001? 11 to 0011? and 111 to 0111?

simply by just appending 0 in front and limiting the length of the string to 4?

Much Thanks!
Chinho

corp769 02-16-2011 01:37 AM

Maybe messing around with std::fixed and std::setprecision?

corp769 02-16-2011 01:42 AM

I'm sorry, here is what you need to use:

Code:

int mynumber = 1;
cout << setfill('0') << setw(2) << mynumber;
cout << setfill('0') << setw(4) << mynumber;


chinho 02-16-2011 02:23 AM

Thanks corp!

corp769 02-16-2011 02:28 AM

Not a problem at all, glad to see it worked for you. Thanks for asking too, it gives me something to do!


All times are GMT -5. The time now is 07:23 AM.