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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With