4

This is my Code [Note: I am using Eclipse for C/C++ on Windows Platform]

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

int main(void) {
    int num;
    printf("Enter a number:\n");
    scanf("%d",&num);
    if(num%2==0)
        printf("Number is Even");
    else
        printf("Number is Odd");
    return EXIT_SUCCESS;
}

Here I have to enter an Integer first only then printf is called... I want to call printf first before I enter an Integer...What am I doing wrong here?

for example this is the output that I get

6
Enter a number:
Number is Even

and expected output is

Enter a number:
6
Number is Even
8
  • 1
    Is the problem that scanf is not returning, or that the final call to printf is not producing output? Commented Jul 21, 2017 at 11:36
  • 1
    If the program does not recognize stdin/stdout as an "interactive device", it will be fully buffered. In this case, output may be buffered until a call to fflush(stdout) (or one of a number of other function calls) is encountered.
    – user3185968
    Commented Jul 21, 2017 at 11:43
  • 9
    try printf("Enter a number:\n");fflush(stdout);
    – BLUEPIXY
    Commented Jul 21, 2017 at 11:46
  • 3
    Note that your question should be "Why isn't the output from printf() appearing when expected?" since you've not produced any evidence that the calls are not made but only that you don't see the output you expect. Commented Jul 21, 2017 at 12:35
  • 3
    It Ok for me. I cant reproduce your problem on GCC.
    – EsmaeelE
    Commented Jul 21, 2017 at 15:29

1 Answer 1

1

you can call fflush(stdout) after first printf to print the buffered output. But considering in future if you extend the program with more printfs then adding fflush after every printf will be an overhead. So you can add

setbuf(stdout, NULL)

just before all the printfs. This will make sure no output is buffered and you will see the prints instantaneously.

Not the answer you're looking for? Browse other questions tagged or ask your own question.