Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

calculate string length

srikanth_gsrikanth_g HyderabadMember Posts: 1

hie,
can you help me here,
when a string like "whatisthis" is passed it gives correct length,
but if string like "what is this" is passed, it returns length as 4 only.

//-----------------------------------------------------

include <stdio.h>

int str_len(char *s)
{
int i;
for(i = 0; *s != '\0'; s++)
i++;
return i;
}

int main()
{
char a[100];

scanf("%s",a);

printf("input string %s \n",a);

printf("input string %s length is %d \n",a,str_len(a));

return 0;

}

Comments

  • B00B00 Member Posts: 111 ✭✭✭

    scanf with %s accepts only string which does not contain whitespaces. You can do it like this scanf("%[\^n]", a). String will be read until newline \n.

    I suggest using fgets(line, LINE_MAX, stdin) instead because scanf does not have buffer overflow protection.

Sign In or Register to comment.