0

I do not understand the functioning of scanf instruction

int i;
scanf("\n");
printf("hello!\n");
scanf("%d",&i);
printf(%d",i);

so the the second scanf don't let me type the second input, and it take only the first value why ?

user3466199
  • 21
  • 2
  • 10

1 Answers1

1

when you (for example) input 2[space][space][space], the whitespaces will be consumed by \n, even your "enter"! (when you actually want to confirm your input).. and your 2 will be stored in variable i..

this \n will keep scanning until it finds a non-whitespace character, such as: your second int input.. but of course it's not stored in any variable (see your code)!

so at last, it returns and print out the value of variable i; which is 2..

  • but why it is stored directely in i variable whitout ask me to type the second input when it execute the second scanf – user3466199 Apr 11 '14 at 00:26
  • because your `2` is not consumed by `\n` (it only consumes non-whitespaces), so it's still there **to be consumed** by **the one who wants it**, in this case, your **second scanner**.. – Yohanes Khosiawan 许先汉 Apr 11 '14 at 00:33