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

标签 c

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/

相关文章:

c - 为什么结构体的初始化是在创建对象的地方完成的,请参见下面的代码?

c - fflush() 始终返回 0 但将 errno 设置为 11(资源暂时不可用)

c - 将 execv 与 Linux 的任意命令一起使用——echo、date、ls 等

从 ip 和子网掩码计算广播地址

c - 在 Linux 中检测 RS-232 com 端口

c - 像 cout 一样,在 printf 处自动定位数字大约为 double

c# - Visual Studio 运行不需要的代码

c - dlopen malloc 死锁

c - 通过函数求解经过的日期和天数

c - 程序集 MMX 点积段错误