Issue
I am working on a program in which I need to add leading zero for 3 numbers
So the code looks like this
#include <iostream>
using namespace std;
// Check Examples
//Compiler version g++ 6.3.0
int main()
{
long int num =5;
char CNum[10];
sprintf(CNum,"%03ld",num) ;
std::cout << CNum;
return 0;
}
// Outputs 005
Now let's define the number of leading zeros in an integer variable named
int blank = 3
After that the code should look like this
#include <iostream>
using namespace std;
// Check Examples
//Compiler version g++ 6.3.0
int main()
{
int blank = 3;
long int num =5;
char CNum[10];
sprintf(CNum,"%03ld",num) ;
std::cout << CNum;
return 0;
}
Then I edited the sprintf arguments like this
sprintf(CNum,"%0%dld",blank,num);
And this outputs
%dld
Instead of
005
Now, my main questions are,
Can I add user variable defined leading zeroes like this in sprintf?
If Yes, how can I make my code do this?
If No, is there any other way to perform the same action to get desired output?
Thank you, looking forward to your kind replies...
Solution
To make the width dynamic (not hard-coded in the format string), you write it like this:
sprintf(CNum,"%0*ld",blank,num);
Instead of a hard-coded width 3
as in "%03ld"
, the asterisk indicates that the next argument (which must be of type int
) is to be taken as the width.
Answered By - j6t Answer Checked By - Gilberto Lyons (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.