tags:

views:

108

answers:

2

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!

+9  A: 

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
I'm on windows xp
Pat
Thanks That worked.
Pat
+1  A: 

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: http://stackoverflow.com/questions/1716296/why-does-printf-not-flush-after-the-call-unless-a-newline-is-in-the-format-string

Salgar
You don't have to worry about the `\r` on Windows. That's handled by the stream itself when you send `\n`.
Adrian McCarthy
Thanks. The fflush(stdout) solved my problem.
Pat
It should not be needed, though!
Steven Sudit