Question

I made a switch statement, however, it only works with constants already set. If I try to use it with user input, only one of the cases work, every other one doesn't. Now no matter what I enter, it always uses the default case. I tried adding another getchar() to clear the \n character from the buffer but this isn't making a difference. Ill post the entire switch statement here :

      char option=' ';
      option=getchar();
      switch(option){

        //Parallel resistance calculations
        case 'p':
            CLEAR
            //PResistance();
            printf("RESISTANCE");
            getchar();
            break;

        //Ohm's Law calculations
        case 'o':
            CLEAR
            printf("OHM");
            //Ohm();
            break;

        //Exits program
        case 'q':
            printf("Good bye! Stay safe in the laboratory! :)\nPress any key to exit");
            getchar();
            exit(0);
            break;

        //Error checking
        default :
            printf("Invalid input, Try again"); 
            break;

    }


}
while (option!='q');

I commented out the functions so I could use the print statements to test if its working.

Was it helpful?

Solution

Whenever you input a character or string from stdin in C, always make sure there is no \n in the input buffer. To do this, always getchar() after taking integer or float inputs.

In your case, maybe you've inputted an integer before inputting the character. So try to write a getchar() before taking the character input.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top