简体   繁体   中英

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.

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.

This if statement will always be entered. You are entering it if argv[1] is not equal to one of the two strings. But that will always be true. If it's -first then it's obviously not -all . And if it's -all , it's obviously not -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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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