The fgets()
includes the end-of-line character entered in the data entry in string , so it shows an extra 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] = '#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] = '%pre%';
cont = strlen(texto);
printf("\nO tamanho da string: %i\n", cont);
}
';
cont = strlen(texto);
printf("\nO tamanho da string: %i\n", cont);
}
See working on ideone and in C ++ Shell .
The workaround is to place the null character that is the string terminator in place of the newline character. I did not make it portable, in Windows the end of line are two characters.