Difference between scanf("%c", &c) and scanf(" %c", &c) -


this question has answer here:

consider following c code snippet:

#include <stdio.h>  int main() {     int a;     char c;     scanf("%d",&a);     scanf("%c",&c);     printf("int=%d\n",a);     printf("char=%c\n",c); } 

i'm able input integer , not character.the output integer value , no value output second printf statement.

however if use space before format specifier:

scanf(" %c",&c); 

it works expected. why case?

someone told me has clearing input buffer. shed light on same?

the difference between scanf("%c", &c1) , scanf(" %c", &c2) format without blank reads next character, if white space, whereas 1 blank skips white space (including newlines) , reads next character not white space.

in scanf() format, blank, tab or newline means 'skip white space if there skip'. not directly 'clear input buffer', eat white space looks similar clearing input buffer (but quite distinct that). if you're on windows, using fflush(stdin) clears input buffer (of white space , non-white space characters); on unix , according c standard, fflush(stdin) undefined behaviour.

incidentally, if typed integer followed carriage return, output of program ends 2 newlines: first in c , second in format string. thus, might have seen:

$ ./your_program 123 int=123 char=  $ 

that is, scanf() reads newline input. consider alternative input:

$ ./your_program 123xyz int=123 char=x $ 

the integer input stopped when read 'x'; character input therefore reads 'x'.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -