C++ 将命令行参数转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15344714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert command line argument to string
提问by theta
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[])
{
...
}
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?
但是,argv[1]
以这种方式公开的变量似乎是指针类型,我需要它作为字符串。我应该怎么做才能将此命令行参数转换为字符串?
回答by masoud
It's already an array of C-style strings:
它已经是一个 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);
}
}
Argument argc
is count of arguments plus the current exec file.
参数argc
是参数的计数加上当前的 exec 文件。
回答by juanchopanza
You can create an std::string
您可以创建一个 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);
}
回答by kayleeFrye_onDeck
No need to upvote this. It would have been cool if Benjamin Lindleymade his one-liner comment an answer, but since he hasn't, here goes:
无需为此点赞。如果本杰明·林德利 (Benjamin Lindley)将他的单行评论作为答案,那会很酷,但既然他没有,那么这里是:
std::vector<std::string> argList(argv, argv + argc);
std::vector<std::string> argList(argv, argv + argc);
If you don't want to include argv[0]
so you don't need to deal with the executable's location, just increment the pointer by one:
如果你不想包含argv[0]
所以你不需要处理可执行文件的位置,只需将指针加一:
std::vector<std::string> argList(argv + 1, argv + argc);
std::vector<std::string> argList(argv + 1, argv + argc);
回答by kayleeFrye_onDeck
I'm not sure if this is 100% portable but the way the OS SHOULDparse the args is to scan through the console command string and insert a nil-term char at the end of each token, and int main(int,char**)
doesn't use const char**
so we can just iterate through the args starting from the third argument (@notethe first arg is the working directory) and scan backward to the nil-term char and turn it into a space rather than start from beginning of the second argument and scanning forward to the nil-term char. Here is the function with test script, and if you do need to un-nil-ify more than one nil-term char then please comment so I can fix it; thanks.
我不确定这是否是 100% 可移植的,但操作系统应该解析 args 的方式是扫描控制台命令字符串并在每个标记的末尾插入一个 nil-term 字符,并且int main(int,char**)
不使用,const char**
所以我们可以只需从第三个参数开始遍历 args(@note第一个 arg 是工作目录)并向后扫描到零项字符并将其转换为空格,而不是从第二个参数的开头开始向前扫描到空字符。这是带有测试脚本的函数,如果您确实需要取消零化多个零项字符,请发表评论,以便我可以修复它;谢谢。
#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 << "\n\nTesting 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 << "\n\nContiguous Args:\n";
char* end = args[args_count - 1];
while (*end) ++end;
cout << "\n\nContiguous Args:\n";
char* cursor = args[0];
while (cursor != end) {
char c = *cursor++;
if (c == 0)
cout << '`';
else if (c < ' ')
cout << '~';
else
cout << c;
}
cout << "\n\nPrinting argument string...\n";
_::ArgsToString(args_count, args);
cout << "\n" << args[1];
return 0;
}
回答by clockw0rk
Because all attempts to print the argument I placed in my variable failed, here my 2 bytes for this question:
因为打印我放在变量中的参数的所有尝试都失败了,这里是我这个问题的 2 个字节:
std::string dump_name;
(stuff..)
if(argc>2)
{
dump_name.assign(argv[2]);
fprintf(stdout, "ARGUMENT %s", dump_name.c_str());
}
Note the use of assign, and also the need for the c_str() function call.
注意assign的使用,以及c_str()函数调用的需要。
回答by Careal Manic
It's simple. Just do this:
这很简单。只需这样做:
#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 You are right. This is not a good solution. Please read the one answered by juanchopanza.
@Benjamin Lindley 你是对的。这不是一个好的解决方案。请阅读 juanchopanza 的回答。
回答by brkeyal
#include <iostream>
std::string commandLineStr= "";
for (int i=1;i<argc;i++) commandLineStr.append(std::string(argv[i]).append(" "));