1.11M Members

sprintf, leading zeros

 
-1
 

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:

int countDigits(int inteiro,int max){

  char *string;

  string = (char *) calloc(max+1,sizeof(char));
  sprintf(string,"%d",inteiro);

  return strlen(string);
}

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

(sorry about my eventual bad english)

 
0
 

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:

int countDigits(int inteiro,int max){

  char *string;

  string = (char *) calloc(max+1,sizeof(char));
  sprintf(string,"%d",inteiro);

  return strlen(string);
}

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.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article