Check if field is empty using custom C reading function

Asked

Viewed 5,171 times

1

void vazio(void)
{
    char *str = NULL, c;//apontando para null
    int i = 0, j = 1;

    //alocação de memória para str
    str = (char *) malloc (sizeof(char));
    printf("Informe a string: ");
    //ler a string
    while (c != '\n')
    {
        c = getc(stdin);//ler a entrada padrão do teclado
        str = (char *) realloc (str, j*sizeof(char));//realocação de     memória 
        str[i] = c;//ler o caracter, fazendo apontar para c
        ++i;
        ++j;
    }
    str[i] = '\0';//marcar final da string com caracter nulo

    //gets(str);//usando gets, o escopo if é executado
    if((strlen(str) == 0) || (strcmp(str,"0") == 0))
    {
        printf("\7\aErro!\n");
        exit(EXIT_FAILURE);
    }
    //isto é executado, mas não imprime nada, ignorando o if acima
        printf("String: %s", str);

    free(str);//libera memória
    str = NULL;//evita o dangling pointers
}
  • Make error to be issued as gets() works.

  • If the user leaves the field blank, that is to say enter, the program will send a beep, printing error and consequently will close using Exit(EXIT_FAILURE);

1 answer

1


I had to make some changes to compile. The code didn’t even compile in my compiler with the settings I use. I put a if within the while because the reallocation and addition of character to the string should only be done if the character is not the ENTER. This character should always be despised. When you type something it even works even if the intention is different. But when you don’t type anything it creates a problem because the string has size 1 which is occupied by \n.

You can write this code in a better way but you didn’t want to misread your code anymore.

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

//tirei os comentários porque eles davam indicações erradas mesmo
//o erro de runtime é provocado propositalmente pelo código através da função exit
void vazio(void) {
    char *str = malloc(1);
    char c;
    int i = 0;
    printf("Informe a string: ");
    do {
        c = getc(stdin);
        if (c != '\n') {
            str = realloc(str, i + 1);
            str[i++] = c;
        }
    } while (c != '\n');
    str[i] = '\0';
    if(strlen(str) == 0 || strcmp(str, "0") == 0) {
        printf("\7\a\nErro!\n");
        exit(EXIT_FAILURE);
    }
    printf("\nString: %s", str);
    free(str);
}

int main(void) {
    vazio();
}

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

You are using old and unnecessary C-programming techniques.

  • funfou legal. Thanks

  • In which part of the code there are old and unnecessary techniques?

  • The use of malloc does not need to do cast, char size was standardized as 1 on all compilers and platforms, you tried to use gets. In addition there are some things that make the code less readable or doing things they don’t need. An example is to assign NULL to the pointer to prevent pointer pendance. See the code of the ideone how it got cleaner.

  • thanks friend, until

Browser other questions tagged

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