无法比较 argv?
我有这段代码:
if (argv[i] == "-n")
{
wait = atoi(argv[i + 1]);
}
else
{
printf("bad argument '%s'\n",argv[i]);
exit(0);
}
当执行这段代码时,我收到以下错误:
错误的参数“-n”
我真的不知道为什么会这样做。有人可以解释一下吗?
I have this code:
if (argv[i] == "-n")
{
wait = atoi(argv[i + 1]);
}
else
{
printf("bad argument '%s'\n",argv[i]);
exit(0);
}
When this code gets executed I get the following error:
bad argument '-n'
I seriously don't know why it does that. Can someone explain?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
字符串比较需要 C 语言中的函数 - 通常是
中的strcmp()
。如果第一个参数排在第二个参数之前,
strcmp()
函数将返回负值(不一定是 -1);如果第一个参数排在第二个参数之后,则为正值(不一定是 +1);如果两个值相等则为零。String comparisons need a function in C - usually
strcmp()
from<string.h>
.The
strcmp()
function returns a negative value (not necessarily -1) if the first argument sorts before the second; a positive value (not necessarily +1) if the first arguments sorts after the second; and zero if the two values are equal.==
运算符不适用于字符串的内容,因为在此应用程序中字符串实际上是字符指针,并且会比较指针。要比较字符串的内容,请使用
strcmp
或strncmp
。The
==
operator does not work on the contents of strings because strings are effectively character pointers in this application, and the pointer get compared.To compare the contents of strings use
strcmp
orstrncmp
.您正在比较指针(
argv[i]
和"-n"
是char*
和const char*)。
请改用
strcmp()
。You are comparing pointers (
argv[i]
and of"-n"
are achar*
and aconst char*
).Use
strcmp()
instead.你在这里真正做的是指针比较。 argv[i] 不是字符串,它是指向内存中实际字符串开始位置的指针。使用 strcmp()。
What you're really doing here is pointer comparison. argv[i] is not a string, it's a pointer to a location in memory at which the actual string starts. Use strcmp().
您正在比较指针,而不是字符串内容。
argv[i]
和"-n"
是两个不同的字符串,存储在内存中的两个不同位置,即使字符串内的字符相同。You're comparing pointers, not string contents.
argv[i]
and"-n"
are two different strings, stored at two different locations in memory, even if the characters inside the strings are equal.在 C 语言中,运算符
==
比较是否相等。相同数字类型的值以简单的方式进行比较(即
2 + 2 == 4
为 true)。不同整数(和非整数)类型的值会经历一些转换。见别处。
如果指针位于同一地址,则指针相等。
字符串文字放置在内存中,不与任何其他内容重叠;包括不重叠 argv[i] 指向的任何内容(对于 i = 0 到 argc)。
所以你正在比较两个不相等的指针;这就是为什么。您想使用 if (!strcmp(argv[i], "-n")) { ... }。
In C, the operator
==
compares for equality.Values of the same numeric type are compared the straightforward way (i.e.
2 + 2 == 4
is true).Values of different integer (and non-integer numeric) types undergo some conversion. See elsewhere.
Pointers are equal if the point at the same address.
String literals are placed in memory not overlapping any other thing; including not overlapping anything pointed to by argv[i] (for i = 0 to argc).
So you're comparing two unequal pointers; that's why. You want to use
if (!strcmp(argv[i], "-n")) { ... }
.也在为我工作
is also working for me