问题
--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