Sunday 15 August 2010

c - Why Scanf works wierd while taking a character -



c - Why Scanf works wierd while taking a character -

program explantion:- have written programme takes character input user infinite no. of times , print entered input.here program

#include<stdio.h> int main() { int i=1; char a; while (i!=0) { printf("enter %d th value\n",i); scanf("%c",&a); printf("entered input %c\n",a); i++; } }

output of above program:-

enter 1 th value q entered input q come in 2 th value entered input come in 3 th value r entered input r come in 4 th value entered input come in 5 th value g entered input g come in 6 th value entered input come in 7 th value

as can see programme skipping numbered loops , working odd number of 'i' values.

what have done:-

i have searched net whole day , @ lastly found out have insert space before %c in scanf.here updated program.

#include<stdio.h> int main() { int i=1; char a; while (i!=0) { printf("enter %d th value\n",i); scanf(" %c",&a); //changed lineeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee printf("entered input %c\n",a); i++; } }

i made no difference have added space before %c in scanf .now working fine.here output:-

enter 1 th value q entered input q come in 2 th value w entered input w come in 3 th value e entered input e come in 4 th value r entered input r come in 5 th value

my question:- happening exactly? eager know problem.can 1 explain me in detail.i surfed through net did not find explanation kind of problem!!

you leaving newline \n character in buffer press come in input character. on every other iteration scanf reads newline.

" %c" space before %c consume whitespace including newline. if there one.

c while-loop whitespace

No comments:

Post a Comment