将命令行参数转换为字符串 [英] Convert command line argument to string

查看:72
本文介绍了将命令行参数转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,可以读取硬编码的文件路径,而我想使其从命令行读取文件路径.为此,我更改了这样的代码:

I have a program that reads hard-coded file-path and I want to make it read file-path from command line instead. For that purpose I changed the code like this:

#include <iostream>

int main(char *argv[])
{
...
}

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

but, argv[1] variable exposed this way seems to be of type pointer, and I need it as a string. What should I do to convert this command line argument to string?

推荐答案

它已经是C样式字符串的数组:

It's already an array of C-style strings:

#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文件.

Argument argc is count of arguments plus the current exec file.

这篇关于将命令行参数转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆