Why Null character does not adds up to the end of string when scanf'd?

浪子不回头ぞ 提交于 2020-05-28 11:55:07

问题


--start of snip--
char name[15];
...

printf("Enter employee name \n");
scanf("%s",name);

printf("strlen %d \n", strlen(name));
--end of snip --

Output:
Enter employee name
Veronica
8

why is it not adding null character to the end !? am i missing anything?

Please someone explain.

Edited:

Was reading line from opened file using fgets and used strtok(line,"\t ") to get the tokens from the line.

--snip--
char * chk;
char line[100];
char temp_name[15];
while(fgets(line, sizeof line, filep))
{
      chk = strtok(line, " \t");
      while(chk !-= NULL)
      {
           strcpy(temp_name, chk);
           chk = strtok(NULL, " \t");
      }
}
--snip --

Problem:

I am guessing extra character is getting added to the end of the temp_name(not just the name) due to improper handling in strtok delimitter usage.

solution:

if(!strncmp(temp_name, name, strlen(name))) // this is one fix

Other wise use

sscanf(line, "%s", temp_name); //easy fix

Anyways I was confused whether there is problem with NULL or extra character getting added to in strtok operation.

thanks for the answers.

Further, if any one would like to help out what delimiter should i use in strtok to avoid any space, tab etc.


回答1:


The NUL terminator character is added, but strlen returns the length of the string without its NUL terminator.




回答2:


From man 3 strlen :

The strlen() function calculates the length of the string s, excluding the terminating null byte ('\0').




回答3:


Its there, Null will be added to array at the end of scanf. strlen function will give you number of characters till NULL.It doesn't count NULL during string length calculation



来源:https://stackoverflow.com/questions/23724133/why-null-character-does-not-adds-up-to-the-end-of-string-when-scanfd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!