[英]Compare strings coming as char**
int main( int argc, char ** argv )
{
if ( *argv[2] == *argv[3]) { ... }
return true;
}
It is wrong, isn't it?! 是错的,不是吗?
It's not my code, I found it, and, yes, I understand that we should check that we have more than 2 arquments... 这不是我的代码,我找到了,是的,我知道我们应该检查我们是否有两个以上的参数。
For C++, construct std::string
from each argument and then compare using operator==
. 对于C ++,从每个参数构造std::string
,然后使用operator==
进行比较。
For C use strcmp
. 对于C使用strcmp
。
For both, check argc >= 4
before you do this check. 对于这两者,在执行此检查之前,请检查argc >= 4
。
Try this instead: 试试这个:
#include <string>
int main( int argc, char ** argv )
{
if (argc >= 4 && std::string(argv[2]) == std::string(argv[3])) { ... }
return 0;
}
Use strcmp
, see here: 使用strcmp
,请参见此处:
You can use string
class for pure C++ if you want, see here: 您可以根据需要将string
类用于纯C ++,请参见此处:
Yes, it's wrong. 是的,这是错误的。
You need strcmp
. 您需要strcmp
。
It is a perfectly valid code, but it probably doesn't do what you would expect. 这是一个完全有效的代码,但可能未达到您的期望。 If condition
will be true if argv[2]
and argv[3]
begin with the same letter because you compare first character of both strings. If condition
argv[2]
和argv[3]
以相同的字母开头,则If condition
为true,因为您比较两个字符串的第一个字符。 If you want to compare entire strings use strcmp
. 如果要比较整个字符串,请使用strcmp
。
And 2 more advices: When you deal with arguments always check their count (argc). 还有2条建议:处理参数时,请始终检查其计数(argc)。 When you exit main thread the standard is to return 0 if everything is fine. 退出主线程时,如果一切正常,则标准返回0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.