Home > Enterprise >  How to add user defined variable leading zeros in C sprintf?
How to add user defined variable leading zeros in C sprintf?

Time:12-19

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,"ld",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,"ld",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,

  1. Can I add user variable defined leading zeroes like this in sprintf?

    1. If Yes, how can I make my code do this?

    2. If No, is there any other way to perform the same action to get desired output?

Thank you, looking forward to your kind replies...

CodePudding user response:

A simple way of doing this would be to construct your own format string at runtime, e.g.:

#include <iostream>
#include <string>

int main ()
{
    long int num = 5;
    int n_zeroes = 3;
    
    std::string fmt = "%0"   std::to_string (n_zeroes)   "ld";
    
    char CNum [10];
    sprintf (CNum, fmt.c_str (), num) ;
    
    std::cout << CNum;
}    

Live demo

CodePudding user response:

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 "ld", the asterisk indicates that the next argument (which must be of type int) is to be taken as the width.

CodePudding user response:

Try to understand the following code - it will solve your problem:

#include <iostream>
#include <string.h>
using namespace std;
// Check Examples

//Compiler version g   6.3.0

int main()
{
    int blank = 3;
    long int num =5;
    unsigned int i = 0;

    char blankZeros[16];
    char numStr[16];
    char CNum[16];

    sprintf(numStr,"%ld",num);
    for (i = 0; i < blank - strlen(numStr); i  )
        blankZeros[i] = '0';        // adding a zero
    blankZeros[i  ] = '\0';         // end of string sign

    sprintf(CNum,"%s%s",blankZeros, numStr) ;

    std::cout << CNum;

    return 0;
}

CodePudding user response:

  1. If No, is there any other way to perform the same action to get desired output?

If you are outputting the result to cout anyway, you could do the formatting directly there:

std::cout << std::setfill('0') << std::setw(blank) << num;
  • Related