Home > Software design >  Empty Output When I Put Scanf in C
Empty Output When I Put Scanf in C

Time:01-18

I made a simple code in VS Code, hello world, then I run and it worked. Next, I added an input, scanf. But when I run the code, the output is empty. The output doesn't show anything and only says "running". Please help me solve this.

First code (success):

#include <stdio.h>

int main()
{
    printf("Hello World");
    return 0;
}

Second code (failed):

#include <stdio.h>

int main()
{
    int pin;
    printf("Hello World");
    scanf("%d", &pin);
    return 0;
}

My code just accept printf, not scanf. If I add scanf, the output is empty and keep running. If I remove scanf and only printf in my code, is successful.

CodePudding user response:

The printf function writes to stdout. When stdout is connected to a terminal or console, it's line buffered.

Line buffering means that the output is actually written to the terminal/console on either of three conditions:

  1. The buffer is full
  2. The buffer is explicitly flushed with fflush(stdout)
  3. A newline is printed.

Your output:

printf ("Hello World");

doesn't fulfill any of the three conditions.

Simple solution is to add a trailing newline in the output you print:

printf ("Hello World\n");

CodePudding user response:

Well you have not told your code to actually do anything with the scanf, that's maybe why nothing has come up on your terminal. scanf only takes input from the terminal, but it will not spit it out without you telling it to.

you will need to include this line of code for that to happen:

printf("%d", pin); // underneath your scanf line. 
  •  Tags:  
  • Related