Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my output show up until the program exits?

Tags:

c

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!

like image 525
Pat Avatar asked Jul 28 '10 15:07

Pat


2 Answers

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?

like image 54
siride Avatar answered Oct 24 '22 05:10

siride


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?

like image 27
Salgar Avatar answered Oct 24 '22 04:10

Salgar