C 参数不起作用?
为什么这不起作用? 当我尝试使用 -l 或 -s 作为第一个参数时,if 语句不适用。他们总是转到 else 语句。
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
if (argv[1] == "-l")
{
printf("Yay!\n");
}
else if (argv[1] == "-s")
{
printf("Nay!\n");
}
else
{
printf("%s\n", argv[1]);
}
return 0;
}
Why doesn't this work?
When I try to use -l or -s as the first argument, the if statements don't take. They always go to the else statement.
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
if (argv[1] == "-l")
{
printf("Yay!\n");
}
else if (argv[1] == "-s")
{
printf("Nay!\n");
}
else
{
printf("%s\n", argv[1]);
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能使用
==
运算符来比较字符串 - 请使用strcmp()
代替。通过使用
==
比较字符串,您可以比较char *
指针的地址,而不是字符串值。You cannot compare strings using
==
operator - usestrcmp()
instead.By comparing strings using
==
you are comparing the addresses ofchar *
pointers, not string values.在 C 中,字符串是通过 strcmp 函数进行比较的。相反,您只比较指针。所以:
In C strings are compares by strcmp function. Instead your compares just pointers. So: