Search code examples
ceclipseconsoleeclipse-cdt

Program output in wrong order


I working on a C project in Eclipse environment the code is correct and executable but the output lines are not in order the program ask user to enter a number from 1-5 then asks for a name then street but nothing appear on console screen unless i entered these values

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

int main(void) {

    char name[20], address[30];

    char c;
    printf("How do you feel on a scale of 1-5?");
    c = getchar();

       printf("Enter name: ");
       scanf("%s", &name);

       printf("Enter your address: ");
       scanf("%s", &address);

       printf("Entered Name: %s\n", name);
       printf("Entered address:%s\n", address);

       printf("You said you feel: ");
       putchar(c);

    return EXIT_SUCCESS;
}

Solution

  • The problem is that stdout is line buffered (when going to a console), so unless you print a newline character, the output will remain buffered and not be displayed (OK, there's going to be a maximum size that can be buffered put that's just detail, your small amount of output will remain in buffer).

    The two solutions that occur to me are, use fflush (stdout); after your first 3 printf calls, this will cause the stdout buffer to be flushed to the console, and should resolve your problems.

    You could also turn off buffering of stdout, see setvbuf for how to do this, but I think, placing this call near the start of main (before any output) should work (untested):

    setvbuf (stdout, NULL, _IONBF, 0);