首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

请问,switch case 用法

2012-08-08 
请教,switch case 用法我这个习题代码里面使用switch case 标签却编译出来全部都有问题。难道switch只能和w

请教,switch case 用法
我这个习题代码里面使用switch case 标签却编译出来全部都有问题。难道switch只能和while()一起使用?求高人回答下。

C/C++ code
#include    <stdio.h>int        hs0(int *);void    hs1(void);void    hs2(void);int        main(void){    int        sr;    while((scanf("%d", &sr)) != EOF)    {            printf("Please choose one of the following;\n"            "1)copy files" "    " "2)move files\n"            "3)remove files""  ""4)quit\n");        hs0(&sr);    }    }int        hs0(int * a){    if(*a > 0 && *a < 5)    {        switch(*a)        case '1':            hs1();            break;        case '2':            hs2();            break;        case '3':            printf("Hello3\n");            break;        case '4':            printf("Hello4\n");        default :    break;    }    else        printf("输入错误请对照菜单重新输入\n");}void    hs1(void){    printf("功能成功\n");}void    hs2(void){    printf("功能成功\n");}

-------------------Configuration: c - Win32 Debug--------------------
Compiling...
c.c
D:\学习\code\c.c(26) : error C2043: illegal break
D:\学习\code\c.c(27) : error C2046: illegal case
D:\学习\code\c.c(29) : error C2043: illegal break
D:\学习\code\c.c(30) : error C2046: illegal case
D:\学习\code\c.c(32) : error C2043: illegal break
D:\学习\code\c.c(33) : error C2046: illegal case
D:\学习\code\c.c(35) : error C2047: illegal default
D:\学习\code\c.c(35) : error C2043: illegal break
Error executing cl.exe.

c.exe - 8 error(s), 0 warning(s)

[解决办法]
第一,你用switch的是一个整型变量,case上又是一个char,虽然可以转换,但是不建议使用。
第二,switch需要用一个大括号标志下范围的。所以你得加个括号。
C/C++ code
switch(*a)        {        case 1:            hs1();            break;        case 2:            hs2();            break;        case 3:            printf("Hello3\n");            break;        case 4:            printf("Hello4\n");        default :    break;        } 

热点排行