Question

when i use scanf with %d or %f, it skips white-space characters. on the other hand when used with %c it reads the white-space characters.can someone elaborate on this as to why this happens?

with %d or %f like the code below it skips white-space characters automatically

#include<stdio.h>
void main(void)
{
int i;
scanf("%d ",&i);
}

if i read the input like this

#include<stdio.h>
void main(void)
{
char ch;
scanf(" %c ",&ch);
scanf(" %c",&ch);  /*or like this*/
}

it skips white-space characters. why is scanf showing different behaviours with format-specifiers????

Was it helpful?

Solution

Basically, it's because a white space character is not valid for %d or %f, so they will skip them.

But a white space character is a valid character, so %c will try to process it.

C99 §7.19.6.2 The fscanf function section 8

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top