Open In App

Effect of adding whitespace in the scanf() function in C

In this article, we will discuss the scenarios regarding adding white space before or after the format specifier in a scanf() function in C Programming Language.

Adding a whitespace character in a scanf() function causes it to read elements and ignore all the whitespaces as much as it can and search for a non-whitespace character to proceed.



scanf("%d ");
scanf(" %d");

scanf("%d\n"); This is different
from scanf("%d"); function.

Example 1: The scanf function after reading the number starts reading further until it finds a non-whitespace character on the input and prints the first number that was typed.

Adding whitespace or “\n” after format specifier in scanf function
scanf(“%d “); 
         or 
scanf(“%d\n”, );



Below is the C program to implement the above approach:




// C program to demonstrate the
// above approach
  
#include <stdio.h>
  
// Driver Code
int main()
{
    // Declaring integer variable a
    int a;
  
    // Reading value in "a" using scanf
    // and adding whitespace after
    // format specifier
    scanf("%d ", &a);
  
    // Or scanf("%d\n", &a);
  
    // Both work the same and
    // print the same value
    printf("%d", a);
  
    return 0;
}

Output:

Explanation: In the above example, when the program is executed, first the program will ask for the first input.

Example 2: The scanf function ignores the whitespace character and reads the element only once.

Adding whitespace before format specifier in scanf function
scanf(” %d”);

Below is the C program to implement the above approach:




// C program to demonstrate the
// above approach
#include <stdio.h>
  
// Driver Code
int main()
{
    // Declaring integer variable
    int a;
  
    // Reading value in a using scanf
    // and adding whitespace before
    // format specifier
    scanf(" %d", &a);
  
    // Printing value of a
    printf("%d", a);
  
    return 0;
}

Output:

Explanation: In this code, there is an output as soon as the number is entered because almost all the whitespaces before format specifier are ignored by scanf %-conversions except for “%c”, “%n”, and “%[“. Hence, it is advised to avoid whitespaces in scanf function as much as possible unless one is confident of its use and necessity.


Article Tags :