Error checking switch-case (char-int check) – CSKC
Sign In

Search

Solved Problem! #CPP#2994    siteicon   siteicon  

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

Solution


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.


Share

Created: 24-Jan-2018 23:48 | Updated: 22-Mar-2026 20:22|