Search code examples
cscanf

does scanf("%s",ch); skips the leading whitespaces from previous input? Need a proper detailed explanation


#include <stdio.h>
#include <string.h>
#include<stdio.h>
int main()
{
   int ch;
   char str;
   scanf("%d", &ch);
   scanf("%c", &str);
   printf("x = %d, str = %c", ch, str);
   return 0;
}

Input: 10(enter)
Output: x = 10, str =

here in this code scanf("%d", &ch); reads an integer and leaves a newline character in buffer. So scanf("%c", &str); only reads a newline character. Which i understood.

But when i run this code:

#include <stdio.h>
#include <string.h>
#include<stdio.h>
int main()
{
   int ch;
   char str[54];
   scanf("%d", &ch);
   scanf("%s",str);
   printf("x = %d, str = %s", ch, str);
   return 0;
}

Input: 10(enter) test
Output: x = 10, str = test

here it seems like scanf("%s",str); ignores the newline character from the buffer and reads test from console.

Why this is happening? Give me a proper detailed Explanation


Solution

  • Why this is happening?

    That is what %s is specified to do in scanf. In the 2018 C standard, clause 7.21.6.2, paragraphs 7 and 8 say:

    … A conversion specification is executed in the following steps:

    Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier.

    So, all the conversions except %[, %c, and %n skip initial white-space characters, which includes new-line characters.

    Generally, scanf is not intended to be a full-power parser that facilitates examining every character in the input stream. It is intended to be a convenience mechanism, for reading simple data formats without a lot of rigid constraints. Skipping white-space is part of that.