简体   繁体   English

C ++使用strcmp比较命令行参数

[英]C++ Comparing command line arguments with strcmp

In order to check the command line arguments for the needed commands for the rest of the program, I tried to use strcmp to test if the given arguments were correct. 为了检查程序其余部分所需命令的命令行参数,我尝试使用strcmp来测试给定的参数是否正确。

if((argc != 2) || (strcmp(argv[1], "-first") != 0) || (strcmp(argv[1], "-all") != 0))
    return -1;

This code causes the program to immediately close with the following error: 此代码使程序立即关闭,并出现以下错误:

Program ended with exit code: 255

I've determined that the issues comes from the two strcmp function calls, but from what I have researched, I'm using them correctly. 我确定问题来自两个strcmp函数调用,但是根据我的研究,我正在正确使用它们。

This if statement will always be entered. 将始终输入此if语句。 You are entering it if argv[1] is not equal to one of the two strings. 如果argv[1]不等于两个字符串之一,则在输入。 But that will always be true. 但这将永远是正确的。 If it's -first then it's obviously not -all . 如果是-first那么显然不是-all And if it's -all , it's obviously not -first . 如果全部是-all显然不是-first

So your program will always return with some error status. 因此,您的程序将始终以某些错误状态返回。

What you want to do is check that argv[1] is not equal to all the options: 您要做的是检查argv[1]是否等于所有选项:

if(argc != 2 || (strcmp(argv[1], "-first") != 0 && strcmp(argv[1], "-all") != 0))
  return -1;

I also took the liberty of removing some overly cautious parentheses. 我还自由删除了一些过于谨慎的括号。 You should learn the proper lexical operator precedence. 您应该学习正确的词法运算符优先级。 Overusing parentheses an cause the code to be needlessly cluttered. 过度使用括号会导致代码不必要地混乱。 Apply them when they add to clarity, or are actually required, only. 仅当它们增加清晰度或实际上是必需时才应用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM