You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将字符串转换为对应枚举类型整数?C++程序开发求助

解决字符串到无作用域枚举的转换问题,实现动物年龄查询功能

现有代码的核心问题

  • 输入处理错误:用int x接收用户输入的字符串,会导致std::cin读取失败,x始终为初始值0,完全无法获取用户输入的动物名称。
  • 缺少字符串到枚举的映射逻辑:直接将int强制转换为枚举类型无效,没有建立输入字符串和枚举值的对应关系。

解决方案步骤

  1. 修正输入接收方式:使用std::string接收用户输入的动物名称。
  2. 添加字符串转枚举的辅助函数:遍历预定义的names数组,找到与输入字符串匹配的元素,返回对应的枚举值;若未找到匹配项,返回错误标记并提示用户。
  3. 使用枚举值作为索引获取年龄:通过转换得到的枚举值直接作为age数组的索引,输出对应动物的年龄。

完整修正代码

#include <iostream>
#include <string_view>  
#include <array>
#include <string>

namespace Animal
{
    enum Type
    {
        dog,  //0
        cat,  //1
        snake,  //2
        chicken,  //3
        max_animals, //4
    };

    constexpr std::array<Type, max_animals> types {dog, cat, snake, chicken};

    using namespace std::string_view_literals;
    constexpr std::array<std::string_view, max_animals> names { "dog"sv, "cat"sv, "snake"sv, "chicken"sv };

    std::array<int, max_animals> age {8, 5, 11, 2}; // 显式指定类型,避免隐式推导的潜在问题

    static_assert(std::size(types) == max_animals);
    static_assert(std::size(names) == max_animals);
    static_assert(std::size(age) == max_animals);

    // 字符串转枚举的辅助函数
    Type getAnimalTypeFromString(std::string_view input)
    {
        for (std::size_t i = 0; i < names.size(); ++i)
        {
            if (names[i] == input)
            {
                return types[i];
            }
        }
        // 返回超出有效范围的枚举值作为错误标记
        return max_animals;
    }
}

int main()
{
    std::cout << "Enter an animal name to show their age: ";
    std::string input{};
    std::cin >> input;

    Animal::Type animalType = Animal::getAnimalTypeFromString(input);

    // 检查是否输入了有效动物名称
    if (animalType == Animal::max_animals)
    {
        std::cout << "Invalid animal name entered!\n";
        return 1;
    }

    std::cout << "The age for " << Animal::names[animalType] << " is " << Animal::age[animalType] << "\n";

    return 0;
}

关键代码解释

  • 辅助函数getAnimalTypeFromString:遍历names数组,对比输入字符串与数组元素,找到匹配项后返回对应的枚举值;遍历结束未找到匹配时,返回max_animals作为错误标记(它是枚举中定义的最后一个值,超出有效动物的范围)。
  • 输入处理:改用std::string接收用户输入,确保能正确获取动物名称字符串。
  • 错误处理:在main函数中检查转换后的枚举值是否为max_animals,如果是则提示输入无效,避免越界访问数组。

内容的提问来源于stack exchange,提问作者tadm123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 11:04:57