Reputation: 8173
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
Upvotes: 4
Views: 5532
Reputation: 20229
fgets() instead of scanf().
scanf() takes the input to the end of the word.
Debugging Tips:
You should have been able to debug to some extent on your own. When strlen() wasn't giving correct answer, the first thing to do would be to verify your assumptions. You were assuming that sentence/ptrs had the correct value. A simple printf would have proved it wrong.
Upvotes: 1
Reputation: 96258
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;
}
Upvotes: 9
Reputation: 22094
scanf("%s" ,sentence);
This will only read a string up to the next space. That means, the remaining characters, hence words after john is not read.
To get your desired output, use gets() instead.
gets(sentence);
Upvotes: 1