0

While executing the below code,I am getting an error in which i get the output as "upto do you want to enter another character?(Y/N)" and scanf("%c",&choice) is not executed and loops breaks

   #include<stdio.h>
    void main()
    {
     char ch_1,choice;
     do
     { printf("Enter letter:\n");
      scanf("%c",&ch_1);
      //Check uppercase or lower case
      if(ch_1>=65&&ch_1<=90)
      printf("\nuppercase);
      else
      printf("\nlowercase);
      
      printf("\nDo you want to enter another number?(Y/N)");
      scanf("%c",&choice);
     }while(choice=='Y');
  }
  • 2
    Add a space before each `%c` and please see [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). – Weather Vane Sep 28 '22 at 08:53
  • What happened to the other quote mark in `printf("\nuppercase);`?? Use some whitespace and make your code more readable... – Fe2O3 Sep 28 '22 at 08:55
  • `if(ch_1>=65&&ch_1<=90)` ---> `if(ch_1>='A' && ch_1<='Z')` – CGi03 Sep 28 '22 at 09:04
  • @Weather Vane i have added a space and worked but please give a bit of explanation as i am learning.Also after that i change the code of the last while(choice=='Y') to while(scanf(" %",&choice)=='Y'), a problem occured.After displaying "Do you want to enter another number?(Y/N)"the loop didnot continue and pressing enter moves cursor to new line and pressing a letter other than 'Y' terminates the program. – Bhagat Singh Sep 28 '22 at 09:08
  • Doesn't the duplicate question explain? – Weather Vane Sep 28 '22 at 09:09
  • @Weather Vane Sir, I did not understand. – Bhagat Singh Sep 28 '22 at 09:10
  • 1
    The `scanf` conversion stops at the first character it cannot convert, which is typically (but not necessarily) a space or a newline, and that character remains in the input buffer. It will be read by the *next* `scanf()`. Most format specifiers automatically filter leading whitespace characters from the input, but `%c` and `%[]` and `%n` do not. You can instruct `scanf` to do so by adding a space just before the `%`. – Weather Vane Sep 28 '22 at 09:11
  • Ok but does it happen only inside loops or are there other situations.Also,is the space added to prevent scanf from reading the white space instead of the user input – Bhagat Singh Sep 28 '22 at 09:18
  • The space in the format string instructs `scanf` to discard *any amount* of whitespace from the input. The loop does not affect `scanf` itself, but it means there was a *previous* input, which left a newline in the input. – Weather Vane Sep 28 '22 at 09:25
  • So will this be the reason that the whitespace left by the first scanf in the buffer is read the second scanf and compares it to the condition of the loops and stops it.And,thus we do not see scanf executing. – Bhagat Singh Sep 28 '22 at 09:34

0 Answers0