作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
#include <iostream>
enum SEX {MALE, FEMALE};
int main(int argc, char**argv)
{
enum SEX the_sex = MALE;
return 0;
}
如何在终端或控制台上显示 the_sex 值,从终端或控制台接受值以更新 the_sex 的值,以及如何验证 the_sex 变量的输入?
最佳答案
How can I accept values from the terminal or console to update the value of the_sex and how can I valid the input for
the_sex
variable?
输入可以用任何你想要的表示:一个整数(1 代表男性,2 代表女性),一个 char
('M' 代表男性,'F' 代表女性),一个 std::字符串
。下面是 char
版本的代码示例:
char in;
std::cin >> in;
switch (in) {
case 'M':
the_sex = MALE;
break;
case 'F':
the_sex = FEMALE;
break;
default:
// invalid input
break;
}
或者,这是 std::string
版本:
std::string in;
std::cin >> in;
if (in == "MALE") the_sex = MALE;
else if (in == "FEMALE") the_sex = FEMALE;
else // invalid input
How can I display the_sex value on the terminal or console?
您可以简单地使用 switch
语句来打印出您的 SEX
变量的值:
std::ostream& operator<<(std::ostream& os, SEX the_sex) {
switch (the_sex) {
case MALE:
os << "MALE";
break;
case FEMALE:
os << "FEMALE";
break;
}
return os;
}
关于c++ - 在 C++ 中显示、更新和验证枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20971531/
我是一名优秀的程序员,十分优秀!