gpt4 book ai didi

c - 如何以编程方式将整数映射到 const 字符串?

转载 作者:太空狗 更新时间:2023-10-29 15:31:28 26 4
gpt4 key购买 nike

我有一堆错误代码 (0,1,10,11,20,30,40,...) 我需要映射到它们相应的错误消息。由于错误代码不能方便地用作数组的索引(这将是稀疏和浪费的),我认为这可以通过宏和/或枚举以某种方式完成。

我主要是想创建一个函数 const char *my_strerror(int errorcode)

const char *err00 = "an error message";
const char *err01 = "a different one";
const char *err10 = "another one";

const char* chatter_strerror(int error){
switch(error){
case 0:
return err00;
case 1:
return err01;
case 10:
return err10;

.... // 10 more cases
}
}

当然有更优雅的方法来做到这一点?

最佳答案

一个解决方案是创建一个包含 int 的错误消息结构错误代码字段,以及 char *错误消息的字段。然后是一组错误信息 struct s 可以用错误代码和消息初始化。这种方法可以很容易地用新的错误消息更新代码,如果最终的 struct在错误消息数组中用作 .msg 中带有空指针的哨兵字段,遍历数组的函数不需要知道它包含多少元素。

这是一个例子。 get_error()函数遍历数组,在遇到所需的错误代码时跳出循环。如果达到标记值但未找到匹配项,则返回“无法识别的错误代码”消息。请注意,无需修改 get_error()功能作为新的错误消息被添加到 error_codes[]数组。

#include <stdio.h>

struct Errors
{
const char *msg;
int code;
};

struct Errors error_codes[] = {
{ .code = 1, .msg = "input error" },
{ .code = 5, .msg = "format error" },
{ .code = 10, .msg = "allocation error" },
{ .msg = NULL }
};

const char * get_error(int err_code);

int main(void)
{
printf("Error: %s\n", get_error(1));
printf("Error: %s\n", get_error(5));
printf("Error: %s\n", get_error(10));
printf("Error: %s\n", get_error(-1));

return 0;
}

const char * get_error(int err_code)
{
struct Errors *current = error_codes;
const char *ret_msg = "Unrecognized error code";

while (current->msg) {
if (current->code == err_code) {
ret_msg = current->msg;
break;
}
++current;
}

return ret_msg;
}

OP 指定了 int错误代码,还提到了enum秒。这是使用 enum 的修改.使用 enum 的一个优势这是增加的可读性。一个缺点是现在当错误消息改变时必须在两个地方修改代码。

#include <stdio.h>

/* Modify both the Error_Codes enum and the following error_codes[] array
when adding new error messages. */

enum Error_Codes {
ERRINPUT = 1,
ERRFORMAT = 5,
ERRALLOC = 10
};

struct Errors
{
const char *msg;
enum Error_Codes code;
};

struct Errors error_codes[] = {
{ .code = ERRINPUT, .msg = "input error" },
{ .code = ERRFORMAT, .msg = "format error" },
{ .code = ERRALLOC, .msg = "allocation error" },
{ .msg = NULL }
};

const char * get_error(enum Error_Codes err_code);

int main(void)
{
printf("Error: %s\n", get_error(ERRINPUT));
printf("Error: %s\n", get_error(ERRFORMAT));
printf("Error: %s\n", get_error(ERRALLOC));
printf("Error: %s\n", get_error(-1));

return 0;
}

const char * get_error(enum Error_Codes err_code)
{
struct Errors *current = error_codes;
const char *ret_msg = "Unrecognized error code";

while (current->msg) {
if (current->code == err_code) {
ret_msg = current->msg;
break;
}
++current;
}

return ret_msg;
}

程序输出:

Error: input error
Error: format error
Error: allocation error
Error: Unrecognized error code

关于c - 如何以编程方式将整数映射到 const 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47880223/

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