自定义对枚举类型的读写函数

// 自定义对枚举类型的读写函数
// 时间:2012年2月14日,情人节哎。。
// 环境:VC6.0
#include<iostream >
#include<string >
using namespace std;


// 全局,枚举类型定义
enum color{red, green, yellow, blue};


// 读写的函数原型
color readColor();
void writeColor(color c); // c : input,要显示的枚举变量


//   main函数
int main()
{     
color eyeColor, hairColor;
    
// 测试写函数的容错能力
cout << "测试写函数的容错能力" << endl;
writeColor( color(5) ); 
cout << endl << endl;


    // 读函数测试
cout << "Reading eye color" << endl;
eyeColor = readColor();


cout << endl;


cout << "Reading hair color" << endl;
hairColor = readColor();


// 写函数测试 
cout << "Eye color is ";
writeColor(eyeColor);


cout << ", Hair color is ";
writeColor(hairColor);
cout << endl;
return 0;
}


// 读函数
// 功能:读取一个枚举值
// 前件:枚举类型已经定义
// 后件:返回一个枚举值
color readColor()
{
color value; // output, 返回变量
char c;      // input,得到用户的输入


// 输入循环,数据验证
do
{
cout << "Enter the first color letter r,g,b,y :";
cin >> c;
c = toupper(c); // 忽略输入的大小写
if (c == 'R')
value = red;
else if ( c == 'G' )
value = green;
else if ( c == 'Y' )
value = yellow;
else if ( c == 'b' )
value = blue;
else   // 输入非法时继续执行输入
continue;
break; // 输入合法时退出输入循环
} while(true);


    return value;
}


// 写函数
// 功能:把枚举值在屏幕上显示
// 前件:枚举类型已经定义
// 后件:输出枚举变量或非法提示


void writeColor( color c ) // c : input,要显示的枚举变量
{
string str; // 要显示的字符串


if ( c == red )
str = "red";
else if ( c == green )
str = "green";
else if ( c == blue )
str = "blue";
else if ( c == yellow )
str = "yellow";
else
str = "NO this color !";


cout << str ;
}


/*  这是测试结果。
测试写函数的容错能力
NO this color !


Reading eye color
Enter the first color letter r,g,b,y :a
Enter the first color letter r,g,b,y :d
Enter the first color letter r,g,b,y :r


Reading hair color
Enter the first color letter r,g,b,y :g
Eye color is red, Hair color is green
Press any key to continue


*/ 
 
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值