2

It is an extremely simple program that does an addition of two integers. I don't know why, but when I run the program, the console requires me to input the two integers and then shows the printf() statements, even though I wrote each printf() before each scanf().

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

int main(void) {

    int a, b;

    printf( "Enter first integer\n" );
    scanf( "%d", &a );

    printf( "Enter second integer\n" );
    scanf( "%d", &b );

    int sum;
    sum = a + b;

    printf( "Sum is %d\n", sum );
}

I'll attach what the console shows me as a picture.

enter image description here

J.Z
  • 33
  • 1
  • 6
  • 1
    Don't post pictures of text. Post text as text. – Jabberwocky Jun 16 '20 at 06:45
  • Working as expected for me. Try running explicitly in a terminal outside IDE. – CodeTalker Jun 16 '20 at 06:49
  • 3
    Your code is fine and produces the prompts before the numbers are entered. Generally these type questions are due to line-buffering of output, but you force the output stream to be flushed by including the `'\n'` following each prompt. What compiler and OS are you using? For grins, you can add `fflush (stdout);` after each `printf` and before each `scanf` to confirm... There may be a platform that has some odd implementation that I have not run across yet.. – David C. Rankin Jun 16 '20 at 06:49
  • 3
    Looks to be an eclipse oddity, see [1](https://stackoverflow.com/questions/44098943/printf-not-print-on-the-console-in-eclipse), [2](https://stackoverflow.com/questions/16877264/c-c-printf-before-scanf-issue). – dxiv Jun 16 '20 at 06:55
  • Read [*Modern C*](https://modernc.gforge.inria.fr/) and the documentation of your operating system and compiler. For *every* function you use but didn't write, read its documentation, perhaps [here](https://en.cppreference.com/w/c). In particular, read [scanf(3)](https://man7.org/linux/man-pages/man3/scanf.3.html) and notice that it can fail. – Basile Starynkevitch Jun 16 '20 at 07:06
  • 1
    This is a known eclipse issue and has several posts here on SO regarding it. Try to look for it and you'll find many questions very soon. – RobertS supports Monica Cellio Jun 16 '20 at 07:11
  • @DavidC.Rankin It's quite a famous issue for the Eclipse IDE. The duplicate has more information. – RobertS supports Monica Cellio Jun 16 '20 at 08:25

1 Answers1

0

Your code is correct in function call sequence. It looks like some stdin/stdout wrong handling in Eclipse console. It happens with this IDE sometimes. I can suggest to do next possible things to try avoiding this problem:

  • Update Eclipse to latest version (if it is not done yet);
  • Install another terminal plugin to Eclipse and try with it;
  • Try another IDE: Code::Blocks, CodeLite or do it online.
Alex
  • 61
  • 4