I have a simple c program outputing a message asking for user input. Then a scanf function reading in user input. When the program is run, the program execute the scanf function first before printf is executed asking for user input. What is wrong with the program?

int main ()
{
int i;

printf ("Enter integer: ");
scanf ("%d", &i);
return 0;
}

Not for me. What compiler are you using?

Mingw. It happens in the console of the Integrated Development Environment I am using.

stdout and stdin are not tied, so the output from printf is only guaranteed to be flushed if you print a newline or call fflush. In this case, you probably don't want to print a newline, so the only solution is fflush:

int main ()
{
    int i;

    printf ("Enter integer: ");
    fflush (stdout);

    if (scanf ("%d", &i) == 1)
    {
        printf("Detected %d\n", i);
    }

    return 0;
}

Another thing to watch out for is the value of the Enter key. On Windows it is '\r\n' on Linux it is '\n'. I have seen this giving strange skip effects with the Go language.

On Windows it is '\r\n' on Linux it is '\n'.

Which is largely irrelevant because text oriented streams will convert the platform's representation of a newline into '\n'. There are a few edge cases like processing binary streams or parsing files created on a different platform, but for the most part it's a non-issue.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.