简体   繁体   English

strlen函数给出错误的值

[英]strlen function giving wrong value

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 strlen()函数给我值4它在空格后停止计数我应该做什么谢谢

That scanf will read only one word, if you do a printf you will see it. 那个scanf只能读一个单词,如果你做printf你会看到它。 So there is nothing wrong with strlen . 因此strlen没有任何问题。

Use fgets which reads a whole line: 使用读取整行的fgets

if (! fgets(sentence, sizeof(sentence), stdin)) {
   fprintf(stderr, "error or end  of file while no characters have been read\n");
   return;
}
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()。

gets(sentence);

fgets() instead of scanf(). fgets()而不是scanf()。
scanf() takes the input to the end of the word. scanf()将输入作为单词的结尾。

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. 当strlen()没有给出正确的答案时,首先要做的是验证你的假设。 You were assuming that sentence/ptrs had the correct value. 你假设句子/ ptrs有正确的值。 A simple printf would have proved it wrong. 一个简单的printf就证明它是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM