Home > OS >  Why i can't use switch-case with chars?
Why i can't use switch-case with chars?

Time:06-08

I can't use chars in switch-cases.

printf("choose: \n[w=woman] [m=man] ");
scanf_s("%s" ,&c); 

switch (c) {
    case 'w':
        printf("45,5"); break;
    case 'm':
        printf("50"); break;

}

When we type "w" the code suppose to write "45,5" on the screen but the code doesn't do what we want. It works when i use the same code with necessary edits for numbers (int).

CodePudding user response:

If the variable c has the type char then in the call of scanf_s you have to use the conversion specifier %c instead of %s

scanf_s( " %c", &c, ( rsize_t )1 );

Instead of scanf_s to input a character you could use function scanf like

scanf( " %c", &c );

In the both cases pay attention to the leading space in the format string. It allows to skip white space characters as for example the new line character '\n' that can be stored in the input buffer after pressing the Enter key.

CodePudding user response:

Maybe it is not the best solution for your problem, but i would recommend to look up,

int strcmp(const char *s1, const char *s2);

It is a standard function, to compare two strings, in case you would use multiple characters to match.

  • Related