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/