Khaos
Khaos

Reputation: 21

usleep miliseconds is not working properly in C

I know this is a beginner's bug, but I'm struggling to fix it. The objective is to print the first message from the startGame function on the screen. If the player selects "Enter" the game screen should print out slowly using usleep(milliseconds). However, instead of displaying gradually, it prints everything at once without waiting.

I tested by printing the labirinto function first on the main and then labirinto, the first call it works correctly. But when it's inside the labirinto function, I encounter this issue, printing it out all at once.

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

#define SIZEl 30
#define SIZEh 10

struct sNOCOBRA{
    char cabeca[1][1], i, j;
    struct sNO *prox;
};

int labirinto();
int startgame();
int limites();
int gameover();
    
int main() {

    startgame();
//  limites();
//  gameover();
}


int labirinto() {
    int milliseconds;
    for (int i = 0; i < SIZEl + 2; i++) {
        printf("#");
    }
    printf("\n");
    for (int i = 0; i < SIZEh; i++) {
        printf("#");
        for (int j = 0; j < SIZEl; j++) {
            printf(" ");
            usleep(milliseconds);           
            if (j == SIZEl - 1) {
                printf("#\n");

            }
        }
    }
    for (int i = 0; i < SIZEl + 2; i++) {
        printf("#");
    }
    printf("\n");

}

int startgame() {
    char entrada;
    printf("You've got to eat your way out!\n(sútil referência a DOOM shh...)\n\n       S T A R  N O W ?");
    scanf("%c", &entrada);

    if (entrada == '\n') {
        labirinto();
    }
}

int limites() {
    for (int i = 0; i < SIZEl - 2; i++) {
        for (int j = 0; j < SIZEh - 2; j++) {
            printf("o");
        }
    }   
}

int gameover() {
    printf("G A M E O V E R !⠀\n");
}
``

Upvotes: 2

Views: 79

Answers (1)

dbush
dbush

Reputation: 225727

You have two problems here.

First, milliseconds is uninitialized and therefore its value is indeterminate. Attempting to read a variable with an indeterminate value (in this case) triggers undefined behavior in your code. You need to set this to a specific value. Also, usleep sleeps for the given number of microseconds, not milliseconds.

Second, you're using printf to print to stdout, and doing so is line buffered by default. So any printf call that doesn't contain a newline should be followed by a call to fflush(stdout) so that output gets printed immediately.

Upvotes: 6

Related Questions