![](/img/trans.png)
[英]C++ Iterating over vector of class pointers and using base function
[英]C++: Iterating over a string vector and using the index for putenv
我有一个字符串向量,它是通过解析配置文件创建的。 所有字符串都应采用key=value
格式。 我想遍历向量,并使用 putenv 函数将环境变量设置为键值对。
编码:
for(auto it = settings.begin(); it != settings.end(); it++) {
try {
auto i = it - settings.begin();
cout << i << endl;
putenv(settings.at(i));
} catch (...) {
cout << "Config is not in the format key=value ... please correct" << endl;
}
}
这会引发错误:
cannot convert ‘__gnu_cxx::__alloc_traits<std::allocator<std::basic_string<char> > >::value_type {aka std::basic_string<char>}’ to ‘char*’ for argument ‘1’ to ‘int putenv(char*)’
我对 C++ 很陌生,所有这些变量类型和指针都让我感到困惑。
你正在混合 C 和 C++ 的东西。
std::string
。putenv
是一个“旧”函数,它需要一个指向char
缓冲区的指针,即一个 C 字符串。 幸运的是, std::string
可以轻松获得其中之一:
putenv(settings.at(i).c_str());
// ^^^^^^^^
但是,那里仍然存在问题。 putenv
获取您提供的缓冲区的“所有权”,并希望它“永远”持续。 你的不会; 它只会在std::string
被修改或销毁之前存在。 还不够好!
按照惯例,我们在这里使用 C 的strdup
来分配char
缓冲区的副本。 然后putenv
(或操作系统)有责任稍后释放它。
putenv(strdup(settings.at(i).c_str()));
// ^^^^^^^ ^
由于putenv
不在 C 或 C++ 标准中,而是由 POSIX 提供,因此您应该检查操作系统的联机帮助页以确保正确使用它。
该错误是由您调用 putenv() 引起的,它需要一个指向char
的指针。 您的向量包含 C++ 字符串 (std::string)...
你可以试试这个:
for (auto setting : settings) {
// ... putenv() is inconsistent across compilers, so use setenv() instead...
std::string key = item.substr( 0, item.find_first_of( "=" ) ) ;
std::string val = item.substr( key.length()+1 ) ;
if ( setenv( key.c_str(), val.c_str(), 1 ) != 0 ) {
cerr << "setenv(" << key << ',' << val << ") has failed: " << strerror( errno ) << endl;
}
}
从我读过, putenv
应避免在新的代码,并setenv
应该使用,因为它使得它的参数的副本,无论编译器版本。
( setenv
在 stdlib.h 中)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.