At the end of String’s printing always leaves the 0p. What is it?

Asked

Viewed 64 times

0

I made a code to accept only a few characters read in one vector and pass to another vector. In this case, the first user can type whatever he wants and the program keeps only digits, mathematical operations (+ - / ? ) and the letters p and i. I was able to do it quietly, but when printing the vector already without the unwanted characters print with 0p at the end.

int retira_espaco(int tamanho, char vetor[], int t, char retorno []){ //função para retirar os espaços digitados
    int i = 0;
    int contador = 0;
    for (i=0; i<tamanho; i++){
        if (isdigit(vetor[i]) || vetor[i] == 'i' || vetor[i] == 'p' || vetor[i] == '+' || vetor[i] == '-' || vetor[i] == '*' || vetor[i] == '/' || vetor[i] == '^'){
        retorno[contador++] = vetor[i];
    }
}
    retorno[contador] = '\0';
    return (retorno);
}

void main() // função principal
{
int tamanho = 100;
char vetor[tamanho];
char retorno[tamanho];
printf("DIGITE A EXPRESSAO QUE DEVE SER RESOLVIDA:\n");
fgets(vetor, tamanho, stdin);
printf("%s", retira_espaco(tamanho, vetor, tamanho, retorno));
return 0;
}
  • 1

    After solving the errors that prevented the compilation, it worked: http://ideone.com/mRG31j

  • I was going to comment now, @bigown (mainly on the return char * instead of whole in the function). : ) Vc heim, always faster. rs

1 answer

0

You have to test whether vetor[i] is different from binary zero because fgets always puts a binary zero at the end of the typed field. Otherwise the loop follows until the end of vetor, and may consider junk (uninitialized memory) as valid characters.

for (i = 0; i < tamanho && vetor[i] != 0; i++)
{
    if (isdigit(vetor[i]) || vetor[i] == 'i' || vetor[i] == 'p'
       || vetor[i] == '+' || vetor[i] == '-' || vetor[i] == '*'
       || vetor[i] == '/' || vetor[i] == '^')
    {
       retorno[contador++] = vetor[i];
    }
}

Browser other questions tagged

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