0

In the code below, no matter what I input, it always outputs the corresponding case statement WITH a default case statement! But when I removed the while(1){} loop, everything works fine. Why is this happening? loop's(same for for(;;) loop) fault or default case's fault? How can I change the code to print correctly within a loop?

#include <stdio.h>
#include <ctype.h>
#include <conio.h>

int main(){
    char ch;
    puts("Client Management System");
    puts("========================");
    puts("A: add task");
    puts("D: delete task");
    puts("U: modify task");
    puts("Q: quit system");

    while(1){
        ch = getchar();
        ch = toupper(ch);

        switch(ch){
            case 'A':
                puts("adding task......");
                break;
            case 'D':
                puts("deleting task......");
                break;
            case 'U':
                puts("modifying task......");
                break;
            case 'Q':
                return 0;
            default:
                puts("invalid option");
        }
    }
    return 0;
}
user8267163
  • 43
  • 1
  • 6

1 Answers1

0

Additional case needs to be added to handle '\n' condition. This is because when you type a case in the console and press enter key, '\n' also be included. So handling this would eliminate the default case execution.

Vasanth
  • 24
  • 8