7

I have a simple program from a C programming book, and it's supposed to ask for two integers and then add them together and show the sum. I'm able to enter the two numbers, but the output doesn't show up until the very end of the program.

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

/* Addition Program*/
 main()
{
      int integer1, integer2, sum;
      printf("Enter first integer\n");
      scanf("%d", &integer1);
      printf("Enter second integer\n");
      scanf("%d", &integer2);
      sum = integer1 + integer2;
      printf("Sum is %d\n", sum);
      return 0;
}

The output looks like this:

2
6
Enter first integer
Enter second integer
Sum is 8

Any help would be greatly appreciated, thanks!

Pat
  • 73
  • 3
  • I copied/pasted your example and it showed up as I would expect on my linux box. What system are you running on? Are you using any fancy redirection or anything? – jdizzle Jul 28 '10 at 15:23
  • 1
    What machine are you running this on? I tried your program and it worked fine (showing the "Enter first integer" correctly before allowing me to enter integer). May be if you try "fflush(stdout)" just before scanf, it may work. (Just a dirty trick - sorry). – Shrey Jul 28 '10 at 15:24
  • Normally, reading from stdin flushes the buffer to stdout, avoiding this problem. Looks like something is wrong with this compiler. – Steven Sudit Jul 28 '10 at 15:27

2 Answers2

8

It is possible that the output is not being flushed automatically. You can add fflush(stdout) after each printf() and see if that helps.

Which environment are you using to build and run this program?

siride
  • 165,323
  • 4
  • 31
  • 54
2

Further to the above, printf will only automatically flush it's buffer if it reaches a newline.

If you are running on windows, a newline is \r\n instead of \n.

Alternatively you can do:

fflush(stdout);

Another alternative is to turn off buffering by calling:

setbuf(stdout, NULL);

EDIT:

Just found this similar(but not the same) question: Why does printf not flush after the call unless a newline is in the format string?

Community
  • 1
  • 1
Salgar
  • 7,252
  • 1
  • 24
  • 38