Problem with strlen()

Asked

Viewed 201 times

3

Why is this code printing an extra number when 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;
}

Exit:

Resultado

  • What more number are you printing? The size of the text?

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

6

The fgets() includes the line end character typed in the data entry in the string, so it shows one more character.

We will make the code print the ASCII codes of each character to see what is 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The solution is to put the null character which is the terminator of the string instead of the new line character. I didn’t do it in a portable way, in Windows the end of line is two characters.

This code made to illustrate the change better, this is correct, but this is not how sew usually make real code in the rest of it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.