[英]C++ command line argument comparison
I am doing some validation of the arguments passed by command line in C++ and am having some difficulties. 我正在对C ++中命令行传递的参数进行一些验证,并且遇到了一些困难。
I am doing like so 我这样做
./a.exe inputfile.txt outputfile.txt 16 flush_left
And I am trying to do the validation like so 而我正在尝试像这样进行验证
if(argv[4] == "flush_left" || argv[4] == "flush_justify" || argv[4] == "flush_right"){
And its not working out as planned. 它没有按计划进行。 Though I am not seeing why this won't work.
虽然我没有看到为什么这不起作用。 From everything I've read and seen that should be just fine
从我所阅读和看到的一切都应该没问题
try: 尝试:
std::string argv4 = argv[4];
if(argv4 == "flush_left" || argv4 == "flush_justify" || argv4 == "flush_right"){
//...
}
or (untested): 或(未经测试):
if( argc >=4 && (!strcmp(argv[4],"flush_left") || !strcmp(argv[4],"flush_justify") || !strcmp(argv[4],"flush_right")) ) {
//...
}
argv[4] has type char*
, and string literals have type const char*
, you cant compare the content of those types (=text) using the ==
operator, you would have to use something like strcmp
or the std::string
class instead. argv [4]的类型为
char*
,字符串文字的类型为const char*
,你不能使用==
运算符比较那些类型(= text)的内容,你必须使用类似strcmp
或std::string
而是改为。
Using ==
on char*
compares the address of the variables, not the content. 在
char*
上使用==
比较变量的地址,而不是内容。
./a.exe inputfile.txt outputfile.txt 16 flush_left ./a.exe inputfile.txt outputfile.txt 16 flush_left
A zero based argv gives you: argv[0] = a.exe argv[1] = inputfile.txt argv[2] = outputfile.txt argv[3] = 16 argv[4] = flush_left 基于零的argv为您提供:argv [0] = a.exe argv [1] = inputfile.txt argv [2] = outputfile.txt argv [3] = 16 argv [4] = flush_left
so the index is correct, however you should use strcmp(stringa, stringb) and make sure that returns 0 instead. 所以索引是正确的,但你应该使用strcmp(stringa,stringb)并确保返回0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.