Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string length with fgets function in C [duplicate]

I have a problem. I've tried to see the length of some string after using fgets function. If I enter string under the number of letter which can be in the string (like: the maximum letters in string is 9 and I enter 4 letters), I get length of the string+1. why?

Here's my code:

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

int main(void)
{
    char name[10]={0};
    printf("enter your name\n");
    fgets(name, 10, stdin);
    printf("your name is %s and it is %d letters\n", name, strlen(name)); // length problem 

    return 0;
} 
like image 879
Raz Omry Avatar asked Oct 16 '25 02:10

Raz Omry


1 Answers

From fgets manual page (https://linux.die.net/man/3/fgets):

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (aq\0aq) is stored after the last character in the buffer.

So it adds '\n' after your 4 letters, returning string_length+1.

From Removing trailing newline character from fgets() input you can add @Tim Čas solution to your code.

The line is still read with the fgets() function and after we remove the newline character.

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


int main(void)
{
    char name[10] = { 0 };
    printf("enter your name\n");
    fgets(name, 10, stdin);
    printf("your name is %s and it is %d letters\n", name, strlen(name)); // length problem 
    name[strcspn(name, "\n")] = 0;
    printf("NEW - your name is %s and it is %d letters\n", name, strlen(name));
    return 0;
}

That outputs:

enter your name
Andy
your name is Andy
 and it is 5 letters
NEW - your name is Andy and it is 4 letters
Press any key to continue . . .
like image 141
jgorostegui Avatar answered Oct 18 '25 17:10

jgorostegui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!