-2
--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.

kzs
  • 1,793
  • 3
  • 24
  • 44

3 Answers3

4

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

Teo Zec
  • 383
  • 2
  • 11
2

From man 3 strlen :

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

chrk
  • 4,037
  • 2
  • 39
  • 47
0

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

BenMorel
  • 34,448
  • 50
  • 182
  • 322
shivakumar
  • 3,297
  • 19
  • 28