gpt4 book ai didi

c++ - 在 C++ 中显示、更新和验证枚举值

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:53 28 4
gpt4 key购买 nike

#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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com