简体   繁体   中英

How to compare string command line arguments in C?

Sorry, I'm a rookie in C. What I am trying to do is just to print something if --help parameter is entered to the terminal like ./program --help . So the code is this:

char *HELP = "--help";
char *argv1 = argv[1];

if (argv1 == HELP) {
    printf("argv[1] result isaa %s\n", argv[1]);
}

So even if I use --help parameter it does not pass through the if condition. So what could be the reason behind that?

That's not how you compare strings in C. Use strcmp or strncmp :

if (strcmp(argv1, HELP) == 0)

Include string.h to get access to those.

That is comparing the addresses, not the content. Use strcmp() :

if (0 == strcmp(HELP, argv1))
{
    printf("argv[1] result isaa %s\n", argv[1]);
}

Be sure and check that argc > 1 before accessing argv[1] .

In C, there is no string type. You've declared char *HELP , so HELP is a char * , not a string. In the if, you are comparing two pointers, instead of the string they point to. You will want to call strcmp (string compare), a function that receives two char * , and compares the strings pointed by them.

You shoul use strcmp.

result=strcmp(argv1,HELP);
if(result==0)
{
    --what you want
}

char *HELP = "--help"; - Here --help is a string literal which is a read only data in text segment. You are just assining the address to the pointer variable HELP .

`argv[1] will given you the address where the first commandline arguemet is stored.

So argv[1] and HELP are having different address. So the condition (argv[1] == HELP) is just checking the address stored in these two pointer variables. Always this will fail.

Actually you have to compare the content of these two pionters. For this you can impelement the string compare logic or use the strcmp function.

if (0 == strcmp(argv[1], HELP)
{
    //do your stuff
}

I had same problem. my problem is solved by using strncmp .
strcmp doesnt work for my problem anyway

#include <string.h>


    if (strncmp(argv1, HELP,6) == 0) //6 is size of argument
    {
    //do smt
    }

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