简体   繁体   English

如何比较C中的字符串命令行参数?

[英]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 . 对不起,我是C的新秀。我想做的只是打印一些东西,如果--help参数输入到终端,如./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. 所以,即使我使用--help参数,它也不会通过if条件。 So what could be the reason behind that? 那背后的原因可能是什么呢?

That's not how you compare strings in C. Use strcmp or strncmp : 这不是你比较C中的字符串的方法。使用strcmpstrncmp

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

Include string.h to get access to those. 包含string.h以访问它们。

That is comparing the addresses, not the content. 那就是比较地址,而不是内容。 Use strcmp() : 使用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] . 在访问argv[1]之前,请确保检查argc > 1

In C, there is no string type. 在C中,没有字符串类型。 You've declared char *HELP , so HELP is a char * , not a string. 你已经声明了char *HELP ,所以HELP是一个char * ,而不是一个字符串。 In the if, you are comparing two pointers, instead of the string they point to. 在if中,您要比较两个指针,而不是它们指向的字符串。 You will want to call strcmp (string compare), a function that receives two char * , and compares the strings pointed by them. 您将需要调用strcmp (字符串比较),这是一个接收两个char *的函数,并比较它们指向的字符串。

You shoul use strcmp. 你应该使用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. - 这里--help是一个字符串文字,它是文本段中的只读数据。 You are just assining the address to the pointer variable HELP . 您只是将地址指向指针变量HELP

`argv[1] will given you the address where the first commandline arguemet is stored. `argv [1]会给你存储第一个命令行arguemet的地址。

So argv[1] and HELP are having different address. 所以argv[1]HELP有不同的地址。 So the condition (argv[1] == HELP) is just checking the address stored in these two pointer variables. 因此条件(argv[1] == HELP)只是检查存储在这两个指针变量中的地址。 Always this will fail. 总是这会失败。

Actually you have to compare the content of these two pionters. 实际上你必须比较这两个pionters的内容。 For this you can impelement the string compare logic or use the strcmp function. 为此,您可以阻止字符串比较逻辑或使用strcmp函数。

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

I had same problem. 我有同样的问题。 my problem is solved by using strncmp . 我的问题通过使用strncmp解决了。
strcmp doesnt work for my problem anyway 无论如何, strcmp对我的问题都不起作用

#include <string.h>


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

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

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