The line if(str[i]==" "){
is wrong.
" "
is a string and it consists of two bytes: the space character and a terminating NUL character.
You should use if(str[i]==' '){
instead.
' '
is a character and you should compare it with str[i]
, which is also a character.
Also, it seems you forgot to print a space character after the numbers.
One more point is that you should print the length of the last word
even if there isn't a space character after the last word.
By the way, you shouldn't use gets()
,
which has unavoidable risk of buffer overrun, deprecated in C99 and deleted from C11.
You should use fgets()
, which takes buffer size, instead.
fgets()
saves newline characters read to the buffer while gets()
doesn't,
so you should remove the newline characters if you don't want them.
An example of corrected code:
#include <stdio.h>
#include<string.h>
int main()
{
int i,n,count=0;
char str[20 + 1]; // allocate one more character for a newline character
char* lf; // for searching for a newline character
fgets(str, sizeof(str), stdin); // use fgets() instead if gets()
if ((lf = strchr(str, '\n')) != NULL) *lf = '\0'; // remove a newline character if one exists
n=strlen(str);
for(i=0;i<=n;i++){ // change < to <= for processing the terminating NUL character
if(str[i]==' ' || str[i]=='\0'){ // compare with a character, not a string
if (count>0) printf("%d",count); // avoid duplicate printing for duplicate space characters
if(i+1<n) printf(" "); // print a space if the string continues
count=0;
}else{
printf("%c",str[i]);
count++;
}
}
return 0;
}