0

The output of the following code is very weird for me to understand.Can anybody explain me why it's behaving that way?

#include<stdio.h>
int main()
{
    int i=0;
    char ch='a';

    while(ch!='q')
    {
       scanf("%c",&ch);
       printf("\t%d\n",i);
       i++;
    }

}

Output

enter image description here

Aditi Rawat
  • 784
  • 1
  • 12
  • 15
  • 3
    Try `scanf(" %c", &ch);` See also: [scanf() leaves the new line char in the buffer](//stackoverflow.com/q/5240789) – 001 Dec 27 '17 at 18:34

1 Answers1

0

Write this statement after your scanf statement.

while( getchar() != '\n' );  /* flush to end of input line */

The next time the loop executes, it auto-fetch the character from the standard input buffer, so you have to clear it after every scanf, so that it is not available for the next scanf. Which is done by the line of code I have above.

Siraj Alam
  • 9,217
  • 9
  • 53
  • 65