For starters according to the C Standard the function main
without parameters shall be declared like
int main( void )
Secondly the function lsl
int lsl(char s[]){
does not use its parameter s
. The passed character array is not changed within the function.
Thirdly, the function gets
is unsafe and is not supported by the C Standard. Instead use the standard C function fgets
.
In this if statement
if(str[i]!=" ") i--;
there are compared the character produced by the expression str[i]
with the string literal " "
that used in the condition is converted to the type char*
.
That is in this if statement there are compared a character and a pointer that does not make a sense. You need to use the integer character constant ' '
instead of the string literal " "
.
if ( str[i] != ' ' ) i--;
But in any case the function is incorrect because the user can enter trailing spaces. In this case you will get an incorrect result.
The function can be declared and defined the following way as it is shown in the demonstrative program below.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
size_t lsl( char s[], size_t n )
{
size_t length = 0;
if ( fgets( s, n, stdin ) )
{
s[ strcspn( s, "\n" ) ] = '\0';
size_t i = strlen( s );
while ( i != 0 && isspace( ( unsigned char )s[i -1] ) ) --i;
while ( i != 0 && !isspace( ( unsigned char )s[--i] ) )
{
++length;
}
}
return length;
}
int main(void)
{
enum { N = 5000 };
char s[N];
size_t length = lsl( s, N );
if ( length != 0 )
{
printf( "The length of the last word in the string \"%s\"\n", s );
printf( "is %zu\n", length );
}
return 0;
}
If to enter for example the string "Hello World "
then the program output will look like
The length of the last word in the string "Hello World "
is 5