Click here to Skip to main content
15,911,139 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
is there any function in C++ to convert a m digit number to n ?
for example :
m = 4, n = 8
input : 1234
output: 00001234
Posted

Use printf to do the job.

If you are looking at m and n being variables in your program, then you will have to send printf a string containing the format you want.

printf("%08d", 1234);

will output 00001234 as you want.

http://www.cplusplus.com/reference/cstdio/printf/[^]
 
Share this answer
 
You may also use C++ I/O streams for the purpose:
C++
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
  cout << setfill('0') << setw(8) << 1234 << endl;
}
 
Share this answer
 
The other 2 answers are fully adequate. I like the streams approach. If you want a general approach using printf() then:


C++
int value=1234;
int width = 8;
printf ("%0*d \n", width, value);
 
Share this answer
 
Comments
CHill60 7-Feb-14 11:04am    
No idea why your solution has been voted down. Possibly because the reader didn't realise that you bave demonstrated the use of a variable width in the printf (as per the OPs post!). Upvoted to balance it out.
[no name] 7-Feb-14 18:04pm    
Thanks. As I have sometimes observed there is no point in adding a solution if it does not contribute anything new. I thought my answer did that. I also upvoted both others.
C++
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
void main()
{
 int m=4, n=8,input;
 cout<<"input a number by "<<m<<" digit:"<<endl;
 cin>>input;
  cout << setfill('0') << setw(n) << 1234 << endl;getch();
}

</conio.h></iomanip></iostream>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900