gpt4 book ai didi

c++ - 使用字符串和枚举映射时,Switch执行第一种情况而不是默认情况

转载 作者:行者123 更新时间:2023-12-02 10:22:36 25 4
gpt4 key购买 nike

我想使用映射到枚举成员的字符串。枚举值稍后将在开关中使用,以确定将执行哪些功能。我有以下代码:

#include <iostream>
#include <string>
#include <map>

#define MSG_BUFSIZE 100

enum CMDVAL
{
CMD_USEREXIT,
CMD_LOGIN
};

std::map<std::string, CMDVAL> map_cmdval;

void initCmdmap()
{
map_cmdval["exit"] = CMD_USEREXIT;
map_cmdval["login"] = CMD_LOGIN;
}

bool RUNNING = true;

int main()
{
initCmdmap();
char buffer[MSG_BUFSIZE];

while(RUNNING)
{
memset(buffer, '\0', MSG_BUFSIZE);
std::cin.getline(buffer, MSG_BUFSIZE);

switch (map_cmdval[buffer])
{
case CMD_USEREXIT:
RUNNING = false;
printf("Exiting...\n");
break;
case CMD_LOGIN:
printf("Logging in...\n");
break;
default:
printf("Invalid command\n");
break;
}
}
}

这样可以编译,但是如果我尝试输入与映射中已定义的单词不同的单词,则将执行CMD_USEREXIT情况而不是默认情况。我想念什么?最重要的是为什么会这样?

最佳答案

当你看 std::map::operator[]

Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.



这意味着,当您从标准输入中读取值 foo时,将插入一个默认值为0的新元素 map_cmdval["foo"]

enum CMDVAL 的定义等同于
enum CMDVAL
{
CMD_USEREXIT = 0,
CMD_LOGIN = 1
};
map_cmdval["foo"]的值为0,与 CMD_USEREXIT相同。

关于c++ - 使用字符串和枚举映射时,Switch执行第一种情况而不是默认情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59469070/

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