Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strlen() returns the string count with the null terminator

Tags:

c

normally, strlen() does not count the null terminator at the end of the string. But, below code prints the string count with the null terminator. Can anyone explain me why? Thanks

char str2[100];
printf("\nEnter a string: ");
fgets (str2, sizeof(str2), stdin);
printf("\n%d",strlen(str2));
like image 377
hmdb Avatar asked May 01 '13 07:05

hmdb


People also ask

Does strlen return the null terminator?

strlen(s) returns the length of null-terminated string s. The length does not count the null character.

Does strlen count Terminator?

Strlen computes the length of the string str up to, but not including the terminating null character.

What does strlen function return?

The strlen() function returns the length of string . This example determines the length of the string that is passed to main() .

Does string have null terminator?

All character strings are terminated with a null character. The null character indicates the end of the string. Such strings are called null-terminated strings. The null terminator of a multibyte string consists of one byte whose value is 0.


2 Answers

I am assuming the preceding fgets prompt picked up the newline character.

For example:

You put in apple.

Internally your string was stored as apple\n\0.

strlen then returned 6 for apple + '\n'

like image 76
Arxo Clay Avatar answered Oct 05 '22 13:10

Arxo Clay


The fgets() function accepts the input when a newline character(Enter key when using stdin) is encountered, and the newline character \n is considered a valid character by the function and included in the string copied to your str2.Hence when you pass it as a parameter to strlen() it gives one more than the original number of characters in your string to account for the additional \n character.

If you want the original number of characters or don't want a \n to be added, use the gets() function as it doesn't copy the newline character.And further, you only need to pass the string as argument,no need to pass the stream (stdin) as the default stream for gets() is stdin.

char str2[100];
printf("\nEnter a string: ");
gets(str2);
printf("\n%d",strlen(str2));
like image 45
Rüppell's Vulture Avatar answered Oct 05 '22 12:10

Rüppell's Vulture