在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 errorAfter 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).
更多推荐
发布评论