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)

Salem commented: But you decided to bump it anyway :rolleyes: -2

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.