PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 20, 2022

[FIXED] How to add user defined variable leading zeros in C sprintf?

 July 20, 2022     c++, integer, printf     No comments   

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,

  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...


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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing