问题
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