4

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

jfs
  • 399,953
  • 195
  • 994
  • 1,670
mainajaved
  • 7,905
  • 10
  • 36
  • 44
  • 3
    Hint: when you don't understand what `strlen()` is doing, try printing the value that you are passing to it: `printf("<<%s>>\n", ptrs);`. This would have indicated what the trouble was immediately. The technique applies generically to any debugging problem. Either use a debugger to see what is being passed to the function, or use a print statement. – Jonathan Leffler Oct 10 '11 at 08:35

3 Answers3

9

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;
}
jfs
  • 399,953
  • 195
  • 994
  • 1,670
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
1
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);
Shamim Hafiz - MSFT
  • 21,454
  • 43
  • 116
  • 176
  • 4
    don't use `gets()`; use `fgets()` – jfs Oct 10 '11 at 08:29
  • is that due to gets() producing dangerous side effects, such as allowing sensitive memory area to be accessed. I mean, i remember seeing warning, "use of gets() is dangerous". – Shamim Hafiz - MSFT Oct 10 '11 at 08:31
  • 3
    from the man page: *Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.* – jfs Oct 10 '11 at 08:33
  • That's due to there being no way to use it safely. It does not know how big the buffer is; it will overwrite your buffer. Forget that `gets()` ever existed. **ALWAYS** use `fgets()` or an equivalent (`getline()`, etc) that either takes a size so that a buffer overflow is not possible or that expands memory to meet the requirements of the input line. – Jonathan Leffler Oct 10 '11 at 08:34
1

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.

varunl
  • 19,499
  • 5
  • 29
  • 47