0

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;
}
4
Contributors
5
Replies
22
Views
2 Years
Discussion Span
Last Post by deceptikon
0

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

1

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;
}
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.

Edited by vegaseat

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.