Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the strlen here equal to 25?

Just so I can confirm if what I think is going on is really going on. The following code prints out 25 when I give it the (26 letter) alphabet as an input, is it because fgets always automatically sets the n-th element in an array of n elements to be '\n'?

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[26];

    printf("String: ");
    fgets(str, 26, stdin);

    printf("%lu\n", strlen(str));
}

That way when I try to print the strlen of the alphabet it stops right before the '\n' and returns me 25?

like image 616
Guilherme Cintra Avatar asked Dec 22 '25 06:12

Guilherme Cintra


1 Answers

If the entire line fits in the buffer, according to your size argument (26 in your case), which includes the string null-terminator, then fgets will add the newline.

If the full line does not fit in the buffer, then fgets will not add a newline, only as much as can fit in the buffer (including the null-terminator).

So, if you input anything more than 25 characters (newline excluded) then the length will always be 25.


On a different note, you should always check what fgets returns.

And the strlen function returns a value of type size_t for which the correct printf format is %zu.

And if possible, use sizeof when using fgets. As in fgets(str, sizeof str, stdin).

like image 65
Some programmer dude Avatar answered Dec 23 '25 20:12

Some programmer dude