c++ - 将整数或字符转换为相应的枚举

标签 c++

我正在尝试使用 OOP C++ 制作 Tic Tac Toe 游戏。 我有一个像这样的枚举:

enum class Type : uint8_t
{
    O,
    X,
    None
};

我也有一个类播放器,这里有这个功能:

Piece Player::PickPiece(std::istream& in) const
{
    in >> pickedPiece;
    in >> temp;
    auto pickedPiece = static_cast<Piece::Type>(temp);
    return pickedPiece;
}

它仅在我读取 O 为 0(O 为零)、X 为 1 等值时才起作用,但我想读取 X 或 O 之类的字符,然后将其转换为 int 枚举。我怎样才能做到这一点?我知道我可以在一些 if 条件下做到这一点,但我不喜欢这种方法。

最佳答案

您可以使用 switch 语句:

Piece convert(int value)
{
    switch(value)
    {
        case 0:
        case 'o':
        case 'O':
            return Piece::O;
        case 1:
        case 'x':
        case 'X':
            return Piece::X;
        default:
            // Handle the case when the character and the integers are wrong
    }
}

关于c++ - 将整数或字符转换为相应的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53469078/

相关文章:

android - 避免 android native 代码 (C++) 中的竞争条件

c++ - 抽象基类 C++ 中的静态回调

java - errno 相对于 java 异常的优势

c++ - 用户输入文件名打开文件

C++ 为每个元素调用任意函数

c++ - HOG vector 包含负值

c++ - 未初始化的值是由堆栈分配创建的

c++ - 在有人尝试写入文件之前,我如何读取文件?

c++ - OpenGL - 二维纹理贴图

c++ - 在 C++ 中使用 memcpy 将结构写入 char 数组