SCANF()

scanf() skips whitespace for most formats like %d, %f, and %s, but not for %c. To avoid reading leftover whitespace (like newlines) when using %c, add a space before %c in the format string

#include <stdio.h>

int main() {
    int num;
    char ch;

    scanf("%d", &num);

    scanf(" %c", &ch);  // Note the space before %c

    printf("Number: %d, Character: %c\n", num, ch);

    return 0;
}

 * (space before %c): Skips any leading whitespace characters (spaces, tabs, newlines) before 
   reading the character.
    -  when scanf() is used to read input, it doesn't automatically discard the 
       newline character (\n) left in the input buffer after pressing Enter
       (if scanf() was used previously). if this isn't handled appropriately, the 
       newline character can be interpreted as input for the next scanf() call, 
       causing unexpected behavior.

#include <stdio.h>

int main() 
{
  char sentence[50];
  printf("Enter a sentence: ");
  scanf("%[^\n]", sentence);
  printf("You entered: %s", sentence);
  return 0;
}

 * The %[^\n] format specifier instructs scanf() to read characters until it encounters
   a newline character and stores them in the sentence array.

Last updated