C语言如何判断终端输入的参数的值
How to determine the value of the argument entered in the terminal using C language
我想编写一个程序,根据提供的参数执行不同的功能。
例如:
$ ./program -a //line 1
$ ./program -b //line 2
如果我在终端输入第 1 行,我希望它打印“Hi”
如果我在终端输入第 2 行,我希望它打印“再见”
这是我目前的逻辑,在 C:
中不起作用
int main (int argc, char *argv[])
{
if (argv[1] == "-a"){
printf("Hi");
} else if (argv[1] == "-b")
{
printf("Bye");
}
任何人都可以帮助我修复我的代码以实现我的objective吗?
提前致谢!
您应该使用 strcmp()
在 C 中比较字符串。
#include <stdio.h>
#include <string.h> /* for strcmp() */
int main (int argc, char *argv[])
{
if (strcmp(argv[1], "-a") == 0){
printf("Hi");
} else if (strcmp(argv[1], "-b") == 0)
{
printf("Bye");
}
return 0;
}
我想编写一个程序,根据提供的参数执行不同的功能。
例如:
$ ./program -a //line 1
$ ./program -b //line 2
如果我在终端输入第 1 行,我希望它打印“Hi” 如果我在终端输入第 2 行,我希望它打印“再见”
这是我目前的逻辑,在 C:
中不起作用int main (int argc, char *argv[])
{
if (argv[1] == "-a"){
printf("Hi");
} else if (argv[1] == "-b")
{
printf("Bye");
}
任何人都可以帮助我修复我的代码以实现我的objective吗?
提前致谢!
您应该使用 strcmp()
在 C 中比较字符串。
#include <stdio.h>
#include <string.h> /* for strcmp() */
int main (int argc, char *argv[])
{
if (strcmp(argv[1], "-a") == 0){
printf("Hi");
} else if (strcmp(argv[1], "-b") == 0)
{
printf("Bye");
}
return 0;
}