Strlen problem

2

Can anyone tell me why this code is printing an extra number when I initialize 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:

    
asked by anonymous 06.10.2016 / 21:20

1 answer

5

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.

    
06.10.2016 / 21:50