How to put the contents of getenv() into a string [duplicate]

痴心易碎 提交于 2021-01-26 23:21:55

问题


Possible Duplicate:
How to read Linux environment variables in c++

How can the following be changed to do what it's supposed to do?

string s = getenv("PATH");

回答1:


You have to check that the getenv succeeded first:

char const* tmp = getenv( "PATH" );
if ( tmp == NULL ) {
    //  Big problem...
} else {
    std::string s( tmp );
    //  ...
}

(Supposing I've guessed correctly with regards to "what it's supposed to do".)




回答2:


std::string getEnvVar(std::string const& key)
{
    char const* val = getenv(key.c_str()); 
    return val == NULL ? std::string() : std::string(val);
}


来源:https://stackoverflow.com/questions/5867242/how-to-put-the-contents-of-getenv-into-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!