[英]Why aren't we allowed to use even global const qualified variables in switch-case?IBM support portal hints we can
[英]Why i can't use switch-case with chars?
我不能在 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;
}
當我們鍵入“w”時,代碼假設在屏幕上寫入“45,5”,但代碼並沒有做我們想要的。 當我使用相同的代碼對數字(int)進行必要的編輯時,它可以工作。
如果變量c
具有char
類型,那么在調用scanf_s
時,您必須使用轉換說明符%c
而不是%s
scanf_s( " %c", &c, ( rsize_t )1 );
而不是scanf_s
輸入一個字符,你可以使用函數scanf
像
scanf( " %c", &c );
在這兩種情況下,請注意格式字符串中的前導空格。 它允許跳過空白字符,例如按 Enter 鍵后可以存儲在輸入緩沖區中的換行符'\n'
。
也許這不是解決您問題的最佳解決方案,但我建議您查一下,
int strcmp(const char *s1, const char *s2);
這是一個標准函數,用於比較兩個字符串,以防您使用多個字符進行匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.