Home > Software engineering >  Certain C code not displaying output in VS Code
Certain C code not displaying output in VS Code

Time:11-26

So basically, I have this simple Hello World program and when executed, it outputs correctly.

#include <stdio.h>

int main(){
    printf("Hello");
}
Output: Hello

But for some reason adding a scanf command will cause the program to not output anything. It will display that it's running but it won't display anything.

#include <stdio.h>

int num1;

int main(){
    printf("Enter number: \n");
    scanf("%d", &num1);
    printf("%d", num1);
}

Output:

[Running] cd "d:\programming\" && gcc main.c -o main && "d:\programming\"main

I know my code is okay since I tried it on other IDEs and it worked correctly. I even copied code from the internet and tried to run in VSCode but it still didn't work. It still works perfectly fine yesterday but this problem just pops in nowhere.

I use Visual Studio Code 1.62.3 with C/C , C/C Compile Run, and Code Runner extensions.

CodePudding user response:

It's a buffering problem. When standard output (stdout, where printf writes) is connected to an actual terminal then it's line-buffered, which means output is actually written to the terminal when there's a newline.

However, VSCode probably uses its own terminal emulation and uses pipes to connect stdout to that terminal. That means the output will be fully buffered, and you need to explicitly flush it.

So modify the code as such:

printf("Enter number: \n");
fflush(stdout);  // Actually write the output to standard output
scanf("%d", &num1);
printf("%d", num1);

That it works for the first example is because then the process terminates, and all output is flushed automatically.

  • Related