Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strlen function giving wrong value

Tags:

arrays

c

strlen

hello every one I have written code

char sentence[100]; 
scanf("%s" ,sentence); 
char * ptrs = sentence ;
printf("%d", strlen(ptrs));

suppose I enter

john is a boy

the strlen() function is giving me value 4 it stops counting after space what I should do thanks

like image 336
mainajaved Avatar asked Dec 21 '22 07:12

mainajaved


1 Answers

That scanf will read only one word, if you do a printf you will see it. So there is nothing wrong with strlen.

Use fgets which reads a whole line:

if (! fgets(sentence, sizeof(sentence), stdin)) {
   fprintf(stderr, "error or end  of file while no characters have been read\n");
   return;
}
like image 146
Karoly Horvath Avatar answered Dec 24 '22 01:12

Karoly Horvath