简体   繁体   English

为什么我不能使用带字符的开关盒?

[英]Why i can't use switch-case with chars?

I can't use chars in switch-cases.我不能在 switch-case 中使用字符。

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.当我们键入“w”时,代码假设在屏幕上写入“45,5”,但代码并没有做我们想要的。 It works when i use the same code with necessary edits for numbers (int).当我使用相同的代码对数字(int)进行必要的编辑时,它可以工作。

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如果变量c具有char类型,那么在调用scanf_s时,您必须使用转换说明符%c而不是%s

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

Instead of scanf_s to input a character you could use function scanf like而不是scanf_s输入一个字符,你可以使用函数scanf

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.它允许跳过空白字符,例如按 Enter 键后可以存储在输入缓冲区中的换行符'\n'

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); 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.这是一个标准函数,用于比较两个字符串,以防您使用多个字符进行匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM