TOPIC

Run Time Error

Mautoz asked 4 years ago

Estou fazndo o código da seguinte forma e dá Run Time Error:

    char pernas[15];

    while (strlen(fgets(pernas, 14, stdin)) != 0) {
        pernas[strlen(pernas) - 1] = '\0';
        if (strcmp(pernas, "esquerda") == 0)
            printf("ingles\n");
        else if (strcmp(pernas, "direita") == 0)
            printf("frances\n");
        else if (strcmp(pernas, "nenhuma") == 0)
            printf("portugues\n");
        else if (strcmp(pernas, "as duas") == 0)
            printf("caiu\n");
        strcpy(pernas, "");
    }

Era 15, mas troquei por 14 e nada! Quando uso gets no lugar de fgets da Compilation Error! Alguém pode me dar uma ideia do erro? Pro favor!

Remember not post solutions. Your post may be reviewed by our moderators.

  • feodorv replied 3 years ago

        while (strlen(fgets(pernas, 14, stdin)) != 0) {
    

    fgets returns NULL when the input ends, and strlen(NULL) gives RTE. Use the following code instead:

    while( fgets( pernas, 14, stdin) != NULL )

    Also:

           pernas[strlen(pernas) - 1] = '\0';

    You should do it if and only if strlen(pernas) > 0 && pernas[strlen(pernas)-1] == '\n':

    int len = strlen(pernas);
    if( len > 0 && pernas[len-1] == '\n' ) pernas[len-1] = '\0';
  • rodrigofaslima replied 9 months ago

    resolvi o meu com um WHILE(TRUE) e um SWITCH....

    com isso ele acaba fincando mais rapido....