1. ## strlen intermittent problem

Hi all!

I'm going through tutorial exercises in a textbook and I'm stuck with something I'm sure should be simple!

I need to show the percentage of capacity used by the string in the array but it just won't work!

If anybody can offer any adviced I'd be very grateful!

Code:
```#include <stdio.h>
#include <string.h>

#define ARRAYSIZE 20

int main(void)
{
char a[ARRAYSIZE];

printf("\nEnter some text: ");
gets(a);

printf("\nYour string is %d characters long", strlen(a));

printf("\nThis string occupies %d percent of it's array's capacity", strlen(a) / ARRAYSIZE * 100);

return 0;
}``` 2. 1)Never use gets() for any reason. Use fgets() instead.
Cprogramming.com FAQ > Why gets() is bad / Buffer Overflows

2) You got your equation all mixed up and you are doing INTEGER arithmetic!
I am using strlen(a) + 1 .............. out of ..................... ARRAYSIZE
which is X................... out of....................... 100

What is X? 3. The problem is that math on integers only yields integers (whole numbers), and C rounds down. Since strlen(a) will always be less than ARRAYSIZE, dividing it by ARRAYSIZE will always yield zero.

You need to use floating point numbers, which can have decimal values:
Code:
```int len = strlen(a);
printf("\nThis string occupies %d percent of it's array's capacity",
(int)((float)len/ARRAYSIZE * 100));```
The red bits are casts; they tell the compiler to treat the variable as if it were a different type. By casting "len" to a float, we get a float back from the division. Multiplying a float will yield a float, so we then need to cast the result back to int. 4. Try
Code:
`printf("\nThis string occupies %d percent of it's array's capacity", strlen(a) * 100 / ARRAYSIZE);` 5. You guys are still missing the extra 1 used by \0, but if you dont want to be purists, I don't blame you  6. ## Thanks!

Thanks guys! All great ideas that I can take on board and hopefully remember, good job!!! Popular pages Recent additions percentage, strlen 