No console output in simple c++ program

1.1k views Asked by At

I noticed a weird behaviour of some of my programs in c++ and when I was trying to figure out what coused it, I found out, that something wrong is going on with my console outputs. I used iostream and cstdio functions with the same behaviour. When I print something on console It doesn't display at all. Here are codes that I used for observing this strange behaviour. This piece of code outputs everything propertly (even if it shouldn't IMO):

#include <cstdio>
using namespace std;
int main(void) {
    int a = 0;
    scanf("%d", &a);
    a++;
    printf("result is %d", a);
}

This one however(correct I think) doesn't display anything, only the run finished message

#include <cstdio>
using namespace std;
int main(void) {
    int a = 0;
    scanf("%d", &a);
    a++;
    printf("result is %d \n", a);
}

I also tried it with removed space before "\n" with no difference. However, when I place more the same printf functions with "\n" at the end to the program, everything displays correctly (multiple times of course). Iostream behaves in similar way - using endl doesn' t cause anything to appear on console. What am I doing wrong? As to the original code that caused malfunctioning, I noticed that on my output nothing appeared but in my school, the same code output everything correctly. I am working under NetBeans 8.0.2. Thanks in advance for help

1

There are 1 answers

1
TrezzJo On

All output data is buffered, before it getting printed to console. You can use fflush or \n to flush the output stream and print all data.