Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
Problem Statement - Error checking switch-case (char-int check)
Following program may compile and link well but still it may not serve the desired purpose. Find the error.
TC++ #2994
×
Ask AI About This Code
Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.
×
Test CPP
The code has been copied automatically for you in the clipboard. After that open any of the service and press cntrl-v to paste in the given code area. Needs a bit of tweaking as per the link.
The switch(c) input has a character type to be checked but the case case 1: and case 2: statements are checking for integer type so it will not be able the check the character as entered by the user. Nothing will be printed when user presses 1 or 2. The correct way should be as follows:
switch (c)
{
case ‘1’: cout<<“First Case”; break;
case ‘2’: cout<<“Second Case”;
}
Notice that 1 and 2 have now been enclosed in single quotes (‘1’ and ‘2’) to make then characters to be checked.
Notes
Character and integer are implicitly convertible so this kind of program do not show compilation errors.
This program may work properly with integer case checking also if ascii value of 1 and 2 is checked as follows. switch (c) { case 49: cout<<“First Case”; break; case 50: cout<<“Second Case”; } Here 49 and 50 are ascii values for character 1 and 2 respectively.