2

The program below is sufficent enouhgh to find the length of any string length that is given to the input, however, i need to find the length of an integer variable, rather than a string.

Entering a number to this does work, but not if i scan s as a int type.

int main()
{
   char s[1000];
   char i;
   int u=5;
   do
   {
       char s[1000];
       char i;
       int u=5;
       system("cls");
       printf("Enter a string: ");
       scanf("%s",s);
       for(i=0; s[i]!='\0'; ++i);

       printf("Length of string: %d",i);
       getch();
  }
 while(u==5);
getch();
}

So all i need is either this little program modified to accept intger variables, or a way to transform a calculated int variable into a string.

Any ideas?

Edit: Length = Amount of characters so 25 has 2, 3456 has 4 etc

  • Is there a reason you want to input the number as an `int` (using `%d`). Isn't it working for you as string? – 0xF1 Apr 10 '14 at 11:14

3 Answers3

2

Either use itoa to convert the integer to string and then use your code to calculate the length or

int i;
for (i=0; num!=0; i++, num=num/10){}

should give you the length of the number in i.

Smitt
  • 178
  • 7
  • I think `itoa` is not a standard function, you should not advise it. You can better use `sprintf`. – 0xF1 Apr 10 '14 at 11:23
1

I guess the above example should work fine for integers also. Say if my string is 12345 then I will get 5 as my answer.

However, what else you can do is, input an integer, say i and then do the following.

while(i!=0){
  length++;
  i = i/10;
}

Here, I am considering i is an integer variable and not a character array.

Kraken
  • 23,393
  • 37
  • 102
  • 162
1

You can use log10 and ceil functions from math.h instead.

int length = (int)(number ? log10(number) + 1 : 1);
lgabriellp
  • 82
  • 2
  • 5