Agar123
Agar123

Reputation: 85

printf function not working before the input

Im trying to write a program that get from the user some details and print the details to the screen , im waiting for printf to display orders for the input,and its not working. only after i write the details the printf start to display the orders. how can i fix this problem?

#include <stdio.h>

#define THIS_YEAR 2018

int calcAge(int year);

int main() {

    char id[20];
    int year;
    char gender;
    float height;

    printf("Please enter your year birth\n");
    scanf("%d", &year);

    printf("Please enter your id\n");
    scanf("%s", id);

    printf("please enter your gender\n");
    scanf(" %c", &gender);

    printf("please enter your height\n");
    scanf("%f", &height);

    printf(
            "Your id : %s , your age : %d , your gender : %s , your height : %.2f",
            id, calcAge(year), (gender == 'f') ? "FEMALE" : "MALE", height);

    return 0;
}

int calcAge(int year) {

    return THIS_YEAR - year;
}

Output:

1991
203835568
f
1.73
Please enter your year birth
Please enter your id
please enter your gender
please enter your height
Your id : 203835568 , your age : 27 , your gender : FEMALE , your height : 1.73

Upvotes: 1

Views: 316

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409136

The first thing you need to learn is that using printf writes to a FILE * named stdout.

The second thing you need to learn is that a FILE * is either buffered or unbuffered. Buffering means that the output you write (using e.g. printf) is stored in some internal memory before it's actually being written to the terminal.

By default, when stdout is connected to a normal terminal or console, then stdout is line buffered. Line buffered means that the contents of the buffers are written on newline. But if stdout is connected to a pipe (which is common for an IDE using its own handling of output) then stdout becomes fully buffered. Then the output is written only if the buffer becomes full, or you explicitly flush it (with e.g. fflush(stdout)).

In this case it seems that you're running from such an IDE that turns stdout fully buffered.

Upvotes: 5

Related Questions