繁体   English   中英

C Switch语句输出两种情况

[英]C Switch Statement outputs two cases

这是我的代码:

int main(void)
{
char newr;
lol:
scanf("%c", &newr);


switch (newr) {
case 'a':
    goto killswitch;

case 'b':
    printf("You entered %c", newr);
    goto lol;
    break;
default:
    printf("you entered something other than a or b\a\n");
    goto lol;
    break;
killswitch:
    printf("ayyyy!");
    goto lol;
    break;
}

我的问题是,当我运行程序并键入一个字符时,在这种情况下,假设a,它会给我以下结果:

ayyyy!you entered something other than a or b

无论我输入什么字符,这种情况总是会发生,例如,如果我输入l,它将返回以下内容:

you entered something other than a or b
you entered something other than a or b

我很困扰。 有人知道原因吗?

谢谢

您一直按回车键。 由于enter是ab以外a其他东西,因此您的程序正确地指出了这一点。

如果键入“ ab”,则程序应指示它接收到a ,a b以及ab以外的其他内容。

删除goto哈哈;

killswitch:
printf("ayyyy!");
break;
switch (newr) {
case 'a':
goto killswitch;  

并打印“ ayyy!”

然后将其移至“ scanf”

然后您按下的输入为'\\ n',然后再次进入开关。

解决此问题的简单方法是仅更改一条语句。

更改

scanf("%c", &newr);

scanf("\n%c", &newr);

您的程序将立即运行!

暂无
暂无

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

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