1

i am new to learning C language . I have shifted from C++ and was implementing the while and do while loop

The following is a snippet from my code . This works fine in C++ but in C after executing while loop once it executes scanf first and then prints the menu and i am not able to figure it. Kindly help

#include <stdio.h>

int main() {
    int ch;
    char ans='y';
    while(ans=='y'){
        
        printf("\n1. Insert / Create linked list ");
        printf("\n2. Insert at specific position ");
        printf("\n3. Display ");
        printf("\n4. Search element");
        printf("\n5. Delete element");
        printf("\n6. Exit");
        printf("\nEnter choice \n");
        
        scanf("%d",&ch);
      
        switch(ch)
        {
            case 1 :
                break;
                
            case 2 :
                break;
            
            case 3 :
                break;
                
            case 4 :
                break;
                
            case 5 :
                break;
                
            case 6 :
                break;
        }
        
        printf("\nDo you want to continue ?\n");
        scanf(" %c ",&ans);
        printf("\n");
     };
    
    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
aryaman
  • 27
  • 4
  • 1
    Trailing blanks in `scanf()` format strings are dire — doubly so when the input is supposed to be interactive. You have to type some character that is not white space after the input of the number — so the user must guess/know what the next input should be before the current input (the `scanf(" %d ", &ch);` will terminate. – Jonathan Leffler Sep 01 '20 at 05:06

1 Answers1

2

scanf(" %c ",&ans); --> scanf(" %c",&ans); Drop trailing space.

No need to look for white-space after ans.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256