相关疑难解决方法(0)

如何将枚举类型变量转换为字符串?

如何让printf显示枚举类型变量的值?例如:

typedef enum {Linux, Apple, Windows} OS_type; 
OS_type myOS = Linux;
Run Code Online (Sandbox Code Playgroud)

而我需要的是类似的东西

printenum(OS_type, "My OS is %s", myOS);
Run Code Online (Sandbox Code Playgroud)

必须显示字符串"Linux",而不是整数.

我想,首先我必须创建一个值索引的字符串数组.但我不知道这是否是最美妙的方式.有可能吗?

c c++ preprocessor ansi-c

110
推荐指数
12
解决办法
18万
查看次数

将API使用std :: string作为错误代码返回是不好的做法吗?

在向您提供API时,您经常需要声明错误代码(最常见的是int),之后您经常需要提供一个转换int错误代码的函数,std::string以便能够以智能方式向用户报告错误.

我发现了一些关于如何以编程方式维护int/ std::string映射的帖子,如下所示:将错误代码映射到C++中的字符串

现在,我在想,为什么不简单地回归std::string而不是int?空字符串意味着没有错误,其他任何意味着错误+提供人类可读消息.

我们显然假设您不关心内存使用和性能(您的API通常不会调用函数,执行时间并不重要).

如果您需要客户端能够以编程方式执行某些特定操作,则可以将错误代码声明为常量.但是,你不需要任何intstd::string映射了.例如,它将是:

宣言:

static const std::string successMessage;
static const std::string fileDoesNotExistMessage;
static const std::string internalErrorMessage;

std::string openFile( const std::string& fileName );
Run Code Online (Sandbox Code Playgroud)

执行:

static const std::string successMessage = "";
static const std::string fileDoesNotExistMessage = "File does not exist";
static const std::string internalErrorMessage = "Internal error";

std::string openFile( const std::string& fileName )
{
    if ( ... ) // test …
Run Code Online (Sandbox Code Playgroud)

c++ string error-handling

2
推荐指数
1
解决办法
130
查看次数

标签 统计

c++ ×2

ansi-c ×1

c ×1

error-handling ×1

preprocessor ×1

string ×1