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

关于枚举的输入输出解决思路

2013-02-18 
关于枚举的输入输出例如:1 #includestdio.h23 typedef enum {A1,B,C,D} SchoolName4 int main(int arg

关于枚举的输入输出
例如:
  1 #include<stdio.h>
  2 
  3 typedef enum {A=1,B,C,D} SchoolName;
  4 int main(int argc ,char * argv[])
  5 {
  6     SchoolName school=0;
  7     printf("enter school\n");
  8     scanf("%d",&school);
  9     printf("school=%d\n",school);
 10     return 0;
 11 }

编译报警高了:
 test04.c: In function ‘main’:
test04.c:8:2: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘enum SchoolName *’ [-Wformat]

枚举输入输入正确的写法是什么?
[解决办法]
枚举当整数用就行了,所以输入输出当整数看就好。
gcc下无编译警告,see:


[feng@other #15]$cat a.c
#include<stdio.h>

typedef enum {A=1,B,C,D} SchoolName;

int main(int argc ,char * argv[])
{
        SchoolName school=0;
        printf("enter school\n");
        scanf("%d",&school);
        printf("school=%d\n",school);

        return 0;
}
[feng@other #16]$make
gcc -o a a.c
[feng@other #17]$./a
enter school
3
school=3
[feng@other #18]$

[解决办法]
此警告可以如下消除
scanf("%d",(int *)&school);

[解决办法]
#include <stdio.h>
typedef enum {A=1,B,C,D} SchoolName;
const char *e2s(int e) {
    static const char e2str[5][2]={"0","A","B","C","D"};
    if (!(1<=e && e<=4)) e=0;
    return e2str[e];
}
int main(int argc ,char * argv[])
{
    SchoolName school=0;

    while (1) {
        printf("enter school(1
[解决办法]
2
[解决办法]
3
[解决办法]
4):\n");
        rewind(stdin);
        if (1==scanf("%d",(int *)&school)) {
            if (1<=school && school<=4) break;
        }
    }
    printf("school==%d==%s\n",school,e2s(school));
    return 0;
}

[解决办法]
没   错。

热点排行