如何举一个例子来反驳的使用``==比较`为const char *`
基于: What is the proper function for comparing two C-style strings?如何举一个例子来反驳的使用``==比较`为const char *`
我知道OP是正确的。不过,我用g ++ 4.1.2尝试了以下内容。
#include <iostream>
using namespace std;
int main()
{
const char* str1 = "hello worldA";
if (str1 == "hello worldr")
std::cout << "hello world" << std::endl;
else if (str1 == "hello worldA")
std::cout << "hello worldA " << std::endl;
else
std::cout << "not " << std::endl;
return 0;
}
OR
#include <iostream>
using namespace std;
int main()
{
const char* str1 = "hello worldA";
const char* str2 = "hello worldA";
if (str1 == str2)
std::cout << "hello world" << std::endl;
else
std::cout << "not " << std::endl;
return 0;
}
输出显示正确的比较结果。
问题>如何设计一个程序,使其显示==
不适用于const char*
?
谢谢
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
const char* str1 = "hello worldA";
char strbuf[] = "hello worldA";
const char* str2 = strbuf;
if (str1 == str2)
std::cout << "hello world" << std::endl;
else
std::cout << "not " << std::endl;
if (strcmp(str1, str2) == 0)
std::cout << "same contents" << std::endl;
return 0;
}
输出是:
不
相同的内容
由于一个指向一个恒定的,另一种是没有,有没有办法让指针可能是平等的。如果他们是,*strbuf='Q';
会改变*str1
的值,显然这是错误的。
这可能是一个更好的方式来显示它:
#include <iostream>
#include <string.h>
using namespace std;
void compare(const char *str1, const char *str2)
{
if (str1 == str2)
std::cout << "== says equal" << std::endl;
else
std::cout << "== says uneqal" << std::endl;
if (strcmp(str2, str1) == 0)
std::cout << "strcmp says equal" << std::endl;
else
std::cout << "strcmp says unequal" << std::endl;
}
int main()
{
const char* str1 = "hello worldA";
char strbuf[] = "hello worldA";
compare (str1, strbuf);
return 0;
}
输出必须:
==说uneqal
STRCMP说等于
你应该明确地创建一个'const char *'指向'str2',以便比较两个'const char *'s而不是'const char *'和'char *' – Kevin
谢谢,现在已经改进了。 –
备选:
const char* str = "Hello\0Hello";
const char str2 = str+6;
std::cout << str << " =? " << str2
<< std::boolalpha << " : " << (str == str2);
通过把两个相同的字符串彼此相邻,我们知道他们的地址是不相等的。
http://stackoverflow.com/questions/14911085/why-does-the-equal-works-for-const-char-in-c – q0987
“*我如何设计一个程序,使其显示==不适用于const char *“ - 简单。如果你知道不应该比较'const char *',那么你不会编写代码来做这件事。 – PaulMcKenzie