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

Convert command line argument to string

本文关键字:字符串 转换 参数 命令行      更新时间:2023-10-16

我有一个读取硬编码文件路径的程序,我想让它从命令行读取文件路径。为此,我将代码修改为:

#include <iostream>
int main(char *argv[])
{
...
}

但是,以这种方式暴露的argv[1]变量似乎是类型指针,我需要它作为字符串。我应该怎么做才能将这个命令行参数转换为字符串?

这已经是一个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::vector<std::string> all_args;
  if (argc > 1) {
    all_args.assign(argv + 1, argv + argc);
  }
}

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

可以创建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);
}

不需要投票。如果本杰明·林德利(Benjamin Lindley)把他那句俏皮话作为答案,那就太酷了,但既然他没有,下面是:

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

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

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

#include <iostream>
std::string commandLineStr= "";
for (int i=1;i<argc;i++) commandLineStr.append(std::string(argv[i]).append(" "));

我不确定这是否100%可移植,但操作系统应该解析参数的方式是扫描控制台命令字符串,并在每个令牌的末尾插入一个空项字符,int main(int,char**)不使用const char**,所以我们可以从第三个参数开始迭代args (@note第一个参数是工作目录),然后向后扫描到nil-term char并将其转换为空格,而不是从第二个参数开始向前扫描到nil-term char。这里是测试脚本的功能,如果你确实需要取消一个以上的nil-term字符,那么请评论,这样我就可以修复它;谢谢。

#include <cstdio>
#include <iostream>
using namespace std;
namespace _ {
/* Converts int main(int,char**) arguments back into a string.
@return false if there are no args to convert.
@param arg_count The number of arguments.
@param args      The arguments. */
bool ArgsToString(int args_count, char** args) {
  if (args_count <= 1) return false;
  if (args_count == 2) return true;
  for (int i = 2; i < args_count; ++i) {
    char* cursor = args[i];
    while (*cursor) --cursor;
    *cursor = ' ';
  }
  return true;
}
}  // namespace _
int main(int args_count, char** args) {
  cout << "nnTesting ArgsToString...n";
  if (args_count <= 1) return 1;
  cout << "nArguments:n";
  for (int i = 0; i < args_count; ++i) {
    char* arg = args[i];
    printf("ni:%i"%s" 0x%p", i, arg, arg);
  }
  cout << "nnContiguous Args:n";
  char* end = args[args_count - 1];
  while (*end) ++end;
  cout << "nnContiguous Args:n";
  char* cursor = args[0];
  while (cursor != end) {
    char c = *cursor++;
    if (c == 0)
      cout << '`';
    else if (c < ' ')
      cout << '~';
    else
      cout << c;
  }
  cout << "nnPrinting argument string...n";
  _::ArgsToString(args_count, args);
  cout << "n" << args[1];
  return 0;
}

很简单。只需这样做:

#include <iostream>
#include <vector>
#include <string.h>
int main(int argc, char *argv[])
{
    std::vector<std::string> argList;
    for(int i=0;i<argc;i++)
        argList.push_back(argv[i]);
    //now you can access argList[n]
}

@Benjamin Lindley你是对的。这不是一个好的解决方案。请阅读juanchopanza的回答

因为所有尝试打印我放置在变量中的参数都失败了,这里我为这个问题准备了2个字节:

std::string dump_name;
(stuff..)
if(argc>2)
{
    dump_name.assign(argv[2]);
    fprintf(stdout, "ARGUMENT %s", dump_name.c_str());
}

注意assign的使用,也需要调用c_str()函数。