gpt4 book ai didi

c - Switch 语句始终包含 case 和 default

转载 作者:行者123 更新时间:2023-11-30 19:17:40 24 4
gpt4 key购买 nike

当我编译这个程序时,它会输出相应的 switch case 和默认标签内容,唯一不打印的值是一月,任何帮助都会很棒!

示例输入:4

示例输出:

四月错误

虽然我可以让程序变得更好,但我需要以这种特定的方式来实现它。

while (month != EOF)
{
switch (month)
{

case 49:
month2 = getchar();

switch (month2)
{
case 10:
printf("January \n");
break;
case 48:
printf("October \n");
break;
case 49:
printf("November \n");
break;
case 50:
printf("December \n");
break;
}
break;

case 50:
printf("February \n");
break;
case 51:
printf("March \n");
break;
case 52:
printf("April \n");
break;
case 53:
printf("May \n");
break;
case 54:
printf("June \n");
break;
case 55:
printf("July \n");
break;
case 56:
printf("August \n");
break;
case 57:
printf("Septembe \n");
break;
default: printf("Error \n");





}
month = getchar();
}


system("PAUSE");
return (0);

}

最佳答案

您只需要一个额外的情况来处理您在终端上按 Enter 键时出现的杂散“\n”。如果您只需输入 1,一月就可以了

编辑:实际上我刚刚在 Linux 上测试了它,它运行完美,但在 Windows 上可能存在一些细微的差异。

while (month != EOF)
{
switch (month)
{

case 49:
month2 = getchar();

switch (month2)
{
case 10:
printf("January \n");
break;
case 48:
printf("October \n");
break;
case 49:
printf("November \n");
break;
case 50:
printf("December \n");
break;
}
break;

case 50:
printf("February \n");
break;
case 51:
printf("March \n");
break;
case 52:
printf("April \n");
break;
case 53:
printf("May \n");
break;
case 54:
printf("June \n");
break;
case 55:
printf("July \n");
break;
case 56:
printf("August \n");
break;
case 57:
printf("Septembe \n");
break;
// Filter out stray \n
case '\n':
break;
default: printf("Error \n");





}
month = getchar();
}


system("PAUSE");
return (0);

关于c - Switch 语句始终包含 case 和 default,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27829576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com