1

Compare command line arguments to strings in c? for example I want just the word "autoplay" to be the command line argument, how can i validate that this is the only word? i already have it validating for more than 1 word.

if( argc == 2 ) {
    autoplay(num5);
}
5
  • There's nothing special about command line arguments, they're just ordinary strings. Use strcmp() to compare them. if (argc == 2 && strcmp(argv[1], "autoplay") == 0) Commented Oct 28, 2022 at 19:30
  • How about something like for(int i = 0; i < argc; i++) if(strcmp(argv[i], "autoplay") == 0) autoplay(num5);? Commented Oct 28, 2022 at 19:30
  • 1
    @FiddlingBits strcmp() doesn't return a boolean, it returns 0 when the strings match. Commented Oct 28, 2022 at 19:31
  • @Barmar That was a typo. Commented Oct 28, 2022 at 19:31
  • if( argc == 2 ) then there only is one argument. If can therefor only be the only word. So, either your question needs more explanation, or it is already solved by the code you have shown. Commented Oct 28, 2022 at 19:34

1 Answer 1

2

You use strcmp() to compare strings; note it returns 0 on match. If you want it case insensitive then you need to use strcasecmp() instead:

#include <stdio.h>
#include <string.h>

int main(int argc, char **argv) {
    if(argc == 2 && !strcmp(argv[1], "autoplay")) {
        printf("match\n");
        // autoplay(num5);
        return 0;
    }
    printf("no match\n");
}

and example run;

./a.out
no match
./a.out autoplay
match
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.