std :: string(空char *)错误:basic

编程入门 行业动态 更新时间:2024-10-24 10:25:17
std :: string(空char *)错误:basic_string :: _ S_construct null无效错误(std::string(empty char*) error: basic_string::_S_construct null not valid error)

在Debian上,我需要读取一个环境变量,否则返回一个空字符串。 这是我的代码:

std::string getEnv(std::string var) { char* val = ::getenv(var.c_str()); std::string retVal(val); return retVal; }

当找不到环境变量时,出现以下错误:

basic_string::_S_construct null not valid error

调试完成后,当我尝试向它加载一个空的val时,错误代码发生在std::string retVal(val) 。

我从一个空char *加载字符串会工作,但不觉得。

如何修复上述代码,以便在环境变量不存在的情况下使其工作?

On Debian, I need to read an environment variable, otherwise return an empty string. Here is my code:

std::string getEnv(std::string var) { char* val = ::getenv(var.c_str()); std::string retVal(val); return retVal; }

When the environment variable is not found, I'm getting the following error:

basic_string::_S_construct null not valid error

After debugging, the error code happens on std::string retVal(val) when I try to load an empty val to it.

I tought loading an string from an empty char * would work, but seens not to.

How can I fix the above code so that I can make it work in case the enviroment variable does not exists ?

最满意答案

从man getenv :

getenv()函数返回一个指向环境中值的指针,如果不匹配则返回NULL 。

所以你需要考虑val == NULL的情况。

std::string getEnv(std::string var) { const char* val = ::getenv(var.c_str()); if (val == nullptr) return std::string(""); return std::string(val); }

将是一个可能的解决方案(如果var未找到,则返回空字符串)。

From man getenv:

The getenv() function returns a pointer to the value in the environment, or NULL if there is no match.

So you need to account for the case where val == NULL.

std::string getEnv(std::string var) { const char* val = ::getenv(var.c_str()); if (val == nullptr) return std::string(""); return std::string(val); }

would be a possible solution (return empty string if var is not found).

更多推荐

本文发布于:2023-08-06 21:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1457497.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   string   std   basic   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!