-1

When it asks me to enter a character and I enter say 'b', it executes the last line and then the whole loop again along with the last line without executing the scanf statement in between.

#include <stdio.h>
void main()
{
    char ch = 'C';

     while( ch != 'A')
        {
            printf("Enter your character\n");
            scanf("%c" ,&ch);
            printf("\nLoop must execute completely\n");
        }
    
    }
Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26

1 Answers1

0

scanf("%c" ,&ch);

Reason: After entering some character as an input, you will press enter (newline \n),and this newline (\n) will be read by scanf in the second iteration. %c format specifier can read white space characters like space, tab, line feed (newline), and carriage return.

Solution : Change scanf("%c" ,&ch); to scanf(" %c" ,&ch);. Adding a trailing space in scanf will read any extra white space characters.

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26
  • Your solution works, but I do not understand why. Why is adding a space before working? Please explain – Joy Majumdar Dec 16 '20 at 10:24
  • @JoyMajumdar : please read this :https://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf – MED LDN Dec 16 '20 at 11:06
  • @JoyMajumdar The extra blank space tells `scanf` to skip white space characters and it will actually skip any number of white space characters before reading and storing a character. – Krishna Kanth Yenumula Dec 16 '20 at 11:10