sprintf, leading zeros

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Closed Thread

Join Date: Dec 2007
Posts: 13
Reputation: msr is an unknown quantity at this point 
Solved Threads: 0
msr msr is offline Offline
Newbie Poster

Re: convert int to string

 
-1
  #1
Dec 4th, 2007
I know this thread is "a little bit" old, but i would like if you can help me.

Im using sprintf(). This is my code:
  1. int countDigits(int inteiro,int max){
  2.  
  3. char *string;
  4.  
  5. string = (char *) calloc(max+1,sizeof(char));
  6. sprintf(string,"%d",inteiro);
  7.  
  8. return strlen(string);
  9. }

However if the first digit of "inteiro" is a 0, this function doesnt count it. I wonder why?

(sorry about my eventual bad english)
Quick reply to this message  
Join Date: Feb 2005
Posts: 31
Reputation: mcldev is an unknown quantity at this point 
Solved Threads: 2
mcldev mcldev is offline Offline
Light Poster

Re: convert int to string

 
0
  #2
Dec 4th, 2007
Originally Posted by msr View Post
I know this thread is "a little bit" old, but i would like if you can help me.

Im using sprintf(). This is my code:
  1. int countDigits(int inteiro,int max){
  2.  
  3. char *string;
  4.  
  5. string = (char *) calloc(max+1,sizeof(char));
  6. sprintf(string,"%d",inteiro);
  7.  
  8. return strlen(string);
  9. }

However if the first digit of "inteiro" is a 0, this function doesnt count it. I wonder why?

(sorry about my eventual bad english)
sprintf() returns the length of the string it creates. So you use an int variable to capture that and then return it. However that is merely an efficiency.

The printf/sprintf/sscanf functions use format specifers that indicate the how the data should be displayed. In your case you a simple value of integer which will be the word size of the machine. At the same time since there is no "precision" the string will have zeroes supressed. You can definitely tell the printf() family of functions on how wide the string should be, and weather or not you want leading zeroes. For example, %5d would get you a five digit wide string that is zero supressed whereas %05D gives you the zeroes. You can also justify but beyond this, I highly recommend a good C text like K&R. These days you can probably download it as PDF.
Quick reply to this message  
Closed Thread

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC