why we need to avoid using scanf to read a character????

can anyone explain it clearly??

You don't need to avoid using scanf() to read a character, though it is a relatively heavy function compared to getchar().

you can use scanf but each char needs to be assigned to a variable or an array, instead of scanf if you use getchar() it is easy.
besides getchar() catches anything for output.

See this series of posts.

why we need to avoid using scanf to read a character????

can anyone explain it clearly??

It is because scanf is a relatively heavy function to use by it we are unable to take input of any string including space in it while gets() or other string functions can take space as input.

ironic behaviour of scanf() :--
user have to take 5 input i.e, press 5 y's one by one like that
y
y
y
y
y

#include<stdio.h>
int main(void)
{
   int i=5;
   char ans;
   do {
      i++;
      scanf("%c",&ans);
   }while(ans=='y' || ans=='Y');
   printf("%d",i);
return 0;
}

as user will press y and enter loop will terminate as coz enter is also a character thus falsing the loop condition resulting output 7 instead of 7.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.