gpt4 book ai didi

c - 如果我们在 C 中需要整数的 switch case 中输入一个字符,会发生什么

转载 作者:行者123 更新时间:2023-11-30 20:55:31 25 4
gpt4 key购买 nike

int main(void)  
{

“这是我迄今为止编写的代码” 整数选择; 做 { 系统(“CLS”); printf("\n1]添加学生"); printf("\n2]显示学生"); printf("\n3]搜索学生"); printf("\n4]按字母顺序排序"); printf("\n5]退出"); printf("\n选择选项:"); scanf("%d",&select);

        switch(select)
{
case 1:
.
.
break;
.
.
.
case 5:
printf("\nGoodbye!");
break;

default:
printf("\nSelect 1-5");
break;
}
getch();
}while(select != 5);
}

最佳答案

首先,scanf( "%d", &select);不会从输入流中读取任何十进制整数;如果您输入非数字字符,则根本不会从输入流中读取它(意味着 select 不会更新,并且 scanf 将返回 0 值)。

第二,case '1':与整数值 1 不匹配,但与字符常量的值 '1' (ASCII 格式的十进制 48)。因此,如果您输入1根据您的提示,您的代码不会采用 case '1':分支。

因此,我建议进行以下更改:

do {
// print menu as before

while ( scanf( "%d", &select ) != 1 )
{
while ( getchar() != '\n' ) // remove everything up to the next newline
;
printf( "Input a value between 1 and 5: " );
fflush( stdout );
}

switch( select )
{
case 1: // note no single quotes around 1
...
break;

case 2:
...
break;

...
}
} while ( select != 5 );

关于c - 如果我们在 C 中需要整数的 switch case 中输入一个字符,会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32636532/

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