Problem with strlen()

Why is this code printing one more number being that I initialized the variable as 0?

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

int main ( void ) {

    char texto[50]; int cont = 0;

    printf("\nInforme seu nome completo: ");
    fgets(texto,50,stdin);

    cont = strlen(texto);

    printf("\nO tamanho da string: %i\n",cont);

    return 0;
}

Output:

Result

Author: Maniero, 2016-10-06

1 answers

O fgets() it includes the end-of-line character entered in the data entry in the string, so it shows one more character.

Let's make the code print the ASCII codes of each character to see what's inside the string :

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

int main(void) {
    char texto[50];
    printf("\nInforme seu nome completo: ");
    fgets(texto, 50, stdin);
    int cont = strlen(texto);
    printf("\nO tamanho da string: %i\n", cont);
    for (int i = 0; i < cont; i++) printf("%d ", texto[i]);
    texto[cont - 1] = '\0';
    cont = strlen(texto);
    printf("\nO tamanho da string: %i\n", cont);
}

See working on ideone. E no repl.it. also I put on GitHub for future reference .

The solution is to put the null character that it is the Terminator of the string in place of the newline character. I did not do it in a portable way, in Windows the end of line are two characters.

This code made to better illustrate the change, that's correct, but that's not how sew usually does real code in the rest of it.

 6
Author: Maniero, 2020-11-11 14:24:43