将命令行参数转换为字符串

the*_*eta 26 c++

我不懂C++.

我有一个程序读取硬编码文件路径,我想让它从命令行读取文件路径.为此我改变了这样的代码:

#include <iostream>

int main(char *argv[])
{
...
}
Run Code Online (Sandbox Code Playgroud)

但是,argv[1]以这种方式暴露的变量似乎是类型指针,我需要它作为一个字符串.如何将此命令行参数转换为字符串?

mas*_*oud 27

它已经是一个C风格的字符串数组:

#include <iostream>
#include <string>
#include <vector>


int main(int argc, char *argv[]) // Don't forget first integral argument 'argc'
{
  std::string current_exec_name = argv[0]; // Name of the current exec program
  std::string first_arge;
  std::vector<std::string> all_args;

  if (argc > 1) {

    first_arge = argv[1];

    all_args.assign(argv + 1, argv + argc);
  }
}
Run Code Online (Sandbox Code Playgroud)

参数argc是参数的数量加上当前的exec文件.


jua*_*nza 19

你可以创建一个 std::string

#include <string>
#include <vector>
int main(int argc, char *argv[])
{
  // check if there is more than one argument and use the second one
  //  (the first argument is the executable)
  if (argc > 1)
  {
    std::string arg1(argv[1]);
    // do stuff with arg1
  }

  // Or, copy all arguments into a container of strings
  std::vector<std::string> allArgs(argv, argv + argc);
}
Run Code Online (Sandbox Code Playgroud)


kay*_*eck 7

无需为此点赞。如果本杰明·林德利 (Benjamin Lindley)将他的单行评论作为答案,那会很酷,但既然他没有,那么这里是:

std::vector<std::string> argList(argv, argv + argc);

如果你不想包含argv[0]所以你不需要处理可执行文件的位置,只需将指针加一:

std::vector<std::string> argList(argv + 1, argv + argc);