These pits recent code review when came.
A quick look at the code looks like no problem, a simple string comparison. But when you looked at the feeling something is wrong, the result is always run output "UTF-32". Here there is a misunderstanding that the string ( char *
) is not directly comparable , the following code is an address string comparison, this will cause them to address the string never been output it is equal to "UTF-32" The results of the .
string str("gbk");
if (str.c_str() == "gbk")
cout << "GBK";
else if (str.c_str() == "utf-8")
cout << "UTF-8";
else if (str.c_str() == "utf-16")
cout << "UTF-16";
else
cout << "UTF-32";
The right approach:
- Direct use string comparison .
string str("gbk");
if (str == string("gbk"))
cout << "GBK";
else if (str == string("utf-8"))
cout << "UTF-8";
else if (str == string("utf-16"))
cout << "UTF-16";
else
cout << "UTF-32";
- Use strcmp function to compare strings .
string str("gbk");
if (strcmp(str.c_str(), "gbk") == 0)
cout << "GBK";
else if (strcmp(str.c_str(), "utf-8") == 0)
cout << "UTF-8";
else if (strcmp(str.c_str(), "utf-16") == 0)
cout << "UTF-16";
else
cout << "UTF-32";
After following code runs directly segmentation fault, because the release of an invalid memory address (static memory). Fortunately in C ++ 11, will direct the compiler error.
char *str = (char *)malloc(32);
str = "Hello world!";
free(str);
The right approach (using strcpy string copy):
char *str = (char *)malloc(32);
strcpy(str, "Hello world!");
free(str);