命令参数以argv []相比较是不工作 [英] Comparing command parameter with argv[] is not working

查看:94
本文介绍了命令参数以argv []相比较是不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较命令以argv []的参数,但它不工作。这里是我的code。

I am trying to compare the parameter of command with argv[] but it's not working. Here is my code.

./a.out -d 1

在主函数

int main (int argc, char * const argv[]) {

if (argv[1] == "-d")

    // call some function here

}

但是,这是不工作...我不知道为什么这种比较是不工作的。

But this is not working... I don't know why this comparison is not working.

推荐答案

您无法使用 == 比较字符串。相反,使用 STRCMP

You can't compare strings using ==. Instead, use strcmp.

#include <string.h>

int main (int argc, char * const argv[]) {

if (strcmp(argv[1], "-d") == 0)

// call some function here

}

这样做的理由是,该值...是一个指针重新presenting的第一个字符的位置串中,与之后的字符休息。当您指定 - D在code,它使得在内存中一个全新的字符串。由于新的字符串的位置和的argv [1] 是不一样的, == 将返回 0

The reason for this is that the value of "..." is a pointer representing the location of the first character in the string, with the rest of the characters after it. When you specify "-d" in your code, it makes a whole new string in memory. Since the location of the new string and argv[1] aren't the same, == will return 0.

这篇关于命令参数以argv []相比较是不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆