Search code examples
cwhile-loopswitch-statementdefault

Why does the default statement works after cases, when i remove c = getchar() part?


Default statement works when i remove getchar part.

//First version

 int c;
 while ((c = getchar()) != EOF){
    switch(c){

        case 'a': case 'A': printf("aaa"); break;
        default: printf("invalid");

    }
 }

//Second version

int c;
 while ((c = getchar()) != EOF){
    switch(c){

        case 'a': case 'A': printf("aaa"); break;
        default: printf("invalid");

    }
    c = getchar();
 }

At the first version default part works together with (case a) when i entered a however at the second version it's not the case. Why is that ?


Solution

  • When you're getting an input with getchar() repeatedly, you need to clear the input buffer in order to scan another input.

    In the first version you posted, case:'a' is executed normally, and when the program reaches the end of the while loop, it needs to clear the input buffer. So it performs a scan operation itself (by scanning an empty input) and enters the loop once more.

    You can easily clean the buffer at the end of the while loop:

    int c;
     while ((c = getchar()) != EOF){
      switch(c){
    
        case 'a': case 'A': printf("aaa"); break;
        default: printf("invalid");
    
      }
      getchar(); // Clear input buffer in order to scan next input.
    }