4

大家好,我写过代码

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

假设我输入

john is a boy

strlen()函数给我的值是 4 它在空格后停止计数我应该做什么谢谢

4

3 回答 3

9

该 scanf 将只读取一个单词,如果您执行 aprintf您会看到它。所以没有错strlen

使用fgets读取整行:

if (! fgets(sentence, sizeof(sentence), stdin)) {
   fprintf(stderr, "error or end  of file while no characters have been read\n");
   return;
}
于 2011-10-10T08:25:15.327 回答
1
scanf("%s" ,sentence);

这只会将字符串读取到下一个空格。这意味着,不会读取剩余的字符,因此不会读取 john 之后的单词。

要获得所需的输出,请改用gets()。

gets(sentence);
于 2011-10-10T08:26:24.000 回答
1

fgets() 而不是 scanf()。
scanf() 将输入带到单词的末尾。

调试提示:

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.

于 2011-10-10T08:44:38.330 回答