D Brown
D Brown

Reputation: 460

Why is the scanf statement executing before the first printf statement?

The following is a simple C program:

#include <stdio.h>

int main(void)
{
    //Question 2.16

    //Variables that will be used to store the two numbers
    int num1;
    int num2;

    //Message to prompt the user
    printf ("Enter two numbers\n");

    //Accepting the users input
    scanf("%d %d" , &num1, &num2);

    if (num1 > num2) {
        printf("%d is greater\n", num1); // Print num1 if num1 is greater
    }
    else { //Otherwise print that num1 is not greater
        printf("%d is not greater\n", num1);
    }

    return 0; // End of program
}

But when I build and run the program (the IDE that I am using is Eclipse Cpp Neon), I have to input the values for the variables num1 and num2 before the first printf statement is executed. See the following for the console output:

2 5

Enter two numbers

2 is not greater

My question is simply this: Why is this happening? Any explanation would be welcome.

Upvotes: 2

Views: 1633

Answers (3)

Nicholas Domenichini
Nicholas Domenichini

Reputation: 870

Try using fflush between your printf and scanf statements:

// Message to prompt the user
printf("Enter two numbers\n");
fflush(stdout);
// Accepting the user's input
scanf("%d %d", &num1, &num2);

Upvotes: -1

C. R. Ward
C. R. Ward

Reputation: 93

My advice is the following:

(1) Use a stream explicitly rather than implicitly: For instance, prefer fprintf(stdout, "Enter two numbers\n"); fflush(stdout); instead of printf ("Enter two numbers\n");. Apply the same rule for the scanf function—that is, prefer fscanf and the stream (for instance, stdin) that you are using.

(2) Do not season a scan function anymore than one input at a time—this can cause your stream to malfunction in an unexpected way that you cannot calculate: Therefore, prefer fscanf(stdin, "%d", &num1); fscanf(stdin, "%d", &num2); instead of scanf("%d %d", &num1, &num2);.

Upvotes: 1

biplav karna
biplav karna

Reputation: 64

printf(...)

function puts the output into buffer of output stream. So it may happen that sometimes the output is displayed after sometime.

scanf(...)

function uses input stream.

Both function involves independent streams and due to buffering the results may not seem sequential as per code. To forcefully flush any stream

int fflush(FILE *stream);

is used.

Please use

fflush(stdout);

after print statement to get desired output.

Upvotes: 3

Related Questions