Search code examples
ceclipse-cdt

Wrong output when I run code in Eclipse Indigo CDT


I am using Eclipse Indigo CDT and just running simple code which is:

#include <stdio.h>
void main()
{
    int num;
    printf("enter no\n");
    scanf("%d",&num);
    printf("no is %d\n",num);

}

Opuput:

55
enter no
no is 55

But when I run this code it won't print enter no. Instead of that it waits to enter the number. After pressing some number it is printing enter no. What could be the reason?


Solution

  • That would depend on the flush scheme of standard out.

    Traditionally, stdout is line buffered when connected to a terminal and page buffered when it's not connected to a terminal.

    Apparantly, when you run your program in eclipse, standard out is page buffered.

    You can overcome this by flushing stdout:

    #include <stdio.h>
    void main()
    {
        int num;
        printf("enter no\n");
        fflush(stdout);
        scanf("%d",&num);
        printf("no is %d\n",num);
    
    }
    

    It is good practice to flush a file handle whenever you expect the recipient of the information to respond. That way you can be sure that the recipient gets everything you have written regardless of the buffering of the file handle.