【发布时间】:2020-07-12 18:21:06
【问题描述】:
这里是枚举所有环境变量的代码。
#include <iostream>
#include <cstdlib>
int main (int argc, char *argv[], char *envp[]) {
char **p = nullptr;
p = envp;
while (*p) {
std::cout << *p << std::endl;
p++;
}
return 0;
}
我参考了之前关于printing all environment variables in C/C++ 的帖子。但是,它没有回答我的问题。
如何用惯用的 C++14/C++17 编写上述代码?有什么指点吗?
更新 1 个修改后的代码(发布 Alex 建议)
注意:这将不编译为 envp 不是容器。
#include <iostream>
int main (int argc, char *argv[], char *envp[]) {
for (auto it = std::begin(envp); it != std::end(envp); ++it) {
std::cout << *it << std::endl;
}
return 0;
}
【问题讨论】:
-
for(auto it = std::begin(envp), it != std::end(envp); ++it) std::cout << *it << std::endl; -
您所链接的问题中的第一个答案到底有什么问题?
-
@AlexLarionov ``` 不匹配类型 'const std::valarray<_tp>' 和 'char**' for (auto it = std::begin(envp); it != std:: end(envp); ++it) { ^ env_idio.cc:6:59: 错误:没有匹配函数调用 'end(char**&)' for (auto it = std::begin(envp); it != std::end(envp); ++it) { ^ ```
-
@RichardCritten 该链接中的任何答案都没有谈到 C++14/C++17 代码采用的惯用方法。
-
std::end(envp)不起作用,envp 不是标准容器。
标签: c++ environment-variables c++14 c++17