你輸入了S後的回車還在緩衝區中,後來被讀取到letter中了,而不是你輸入的字母,所以才會出錯,你在之前再加一個getchar就行了。還有你的第二個else if中不需要再讀取字母了,直接判斷就行了。下面是整理後的程式碼。我建議你直接讀取一段作為字串來判斷比較方便,這樣比較麻煩。
#include
void main()
{
printf("please enter the first letter of someday:\n");
char letter;
while ((letter = getchar()) != "y") {
switch (letter) {
case "S": {
printf("please enter the second letter:");
getchar();
if ((letter = getchar()) == "a") {
printf("It is Saturday!\n");
} else if (letter == "u") {
printf("It is Sunday!\n");
} else {
printf("error\n");
}
break;
case "M":
printf("It is Monday!\n");
case "T": {
if ((letter = getchar()) == "h") {
printf("It is Tuesday!\n");
printf("It is Thursday!\n");
case "F":
printf("It is Friday!\n");
case "W":
printf("It is Wednesday!\n");
你輸入了S後的回車還在緩衝區中,後來被讀取到letter中了,而不是你輸入的字母,所以才會出錯,你在之前再加一個getchar就行了。還有你的第二個else if中不需要再讀取字母了,直接判斷就行了。下面是整理後的程式碼。我建議你直接讀取一段作為字串來判斷比較方便,這樣比較麻煩。
#include
void main()
{
printf("please enter the first letter of someday:\n");
char letter;
while ((letter = getchar()) != "y") {
switch (letter) {
case "S": {
printf("please enter the second letter:");
getchar();
if ((letter = getchar()) == "a") {
printf("It is Saturday!\n");
} else if (letter == "u") {
printf("It is Sunday!\n");
} else {
printf("error\n");
}
break;
}
case "M":
printf("It is Monday!\n");
break;
case "T": {
printf("please enter the second letter:");
getchar();
if ((letter = getchar()) == "h") {
printf("It is Tuesday!\n");
} else if (letter == "u") {
printf("It is Thursday!\n");
}
break;
}
case "F":
printf("It is Friday!\n");
break;
case "W":
printf("It is Wednesday!\n");
break;
}
}
}