【问题标题】:idiomatic C++14/C++17 approach to enumerating environment variables枚举环境变量的惯用 C++14/C++17 方法
【发布时间】: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 &lt;&lt; *it &lt;&lt; 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


【解决方案1】:

除了您的问题或链接的答案之外,没有其他方法可以枚举环境变量。原因是环境变量的接口是以 C 代码可以访问它们的方式定义的,因此即使在 C++ 中也必须“以 C 方式”进行。 C++ 没有定义自己的方式来访问环境变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-09
    • 2015-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多