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 th开发者_Python百科an 2 arquments...
For C++, construct std::string
from each argument and then compare using operator==
.
For C use strcmp
.
For both, check argc >= 4
before you do this check.
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:
- http://www.codeguru.com/forum/showthread.php?t=231162
You can use string
class for pure C++ if you want, see here:
- http://www.cplusplus.com/reference/string/string/compare/
Yes, it's wrong.
You need 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 you want to compare entire strings use strcmp
.
And 2 more advices: When you deal with arguments always check their count (argc). When you exit main thread the standard is to return 0 if everything is fine.
精彩评论