You are not logged in. Please login at www.codechef.com to post your questions!

×

# printf with leading zeros in C

 1 Let's say I have a floating point number or an integer number, I want to print it in always 5 characters. See, if output by the compiler is 21 then it should print 00021, In case of 123, output should be 00123, In case of 3.45, output should be 00003.45. And now at the end, can you also help me to get alternative of zeros here in this case. I'm mean "printf with leading any character including zeros"? For above case: x(any chaeacter) 1st output should be xxx21, 2nd output should be xx123, 3rd output should be xxxx3.45. I hope you got the question. asked 20 Apr, 22:21 0★mkbod 56●3 accept rate: 50% What if the number if greater than 99999?? (20 Apr, 22:28) For now i'm assuming 5 digit number. (20 Apr, 22:32) mkbod0★

 3 Answer is hidden as author is suspended. Click here to view. answered 20 Apr, 22:43 (suspended) accept rate: 2% okay ... yes you are talking about padding spaces with 0 ?? (20 Apr, 22:47) floating point %05.4f will not work there! (21 Apr, 00:37)
 1 guys, please upvote me. i am new here. nad not able to ask question answered 21 Apr, 03:05 67●2 accept rate: 0%
 0 So first we need to calculate the number of digits before the decimal point. Code - n is the number if (n < 1){ cout << "0000" << n << endl; } else{ len = 0; x = n while (x >= 1){ x /= 10; len += 1; } for (int i = 0; i < 5-len; i++){ cout << "0"; } cout << n << endl; }  answered 20 Apr, 22:40 2.4k●2●19 accept rate: 8%
 0 Here is the code that you are asking: Ideone To know more about printf() format specifier. Click here answered 20 Apr, 23:59 2.6k●10 accept rate: 16%
 0 The question can also be solved using strings. Here's the code: http://ideone.com/Bs9UHy answered 21 Apr, 01:24 82●7 accept rate: 8%
 toggle preview community wiki:
Preview

### Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Question tags:

×1,241
×30

question asked: 20 Apr, 22:21

question was seen: 226 times

last updated: 21 Apr, 03:05