Let's take a look at the following examples:
/* Define data */
...
Char * msg1 = "testtest ";
Char * msg2 = "test ";
Int Len = 20, T = 1;
...
1 -----> If (strlen (msg2)> = strlen (msg1)... // right
2 -----> If (strlen (msg2)-strlen (msg1)> = 0)... // "error"
3 -----> If (strlen (msg2)> = 10)... // right
4 -----> If (strlen (msg2)-10> = 0)... // "error"
5 -----> If (strlen (msg2)-len> = 0)... // "error"
6 -----> If (t-strlen (msg2)> = 0)... // "error"
7 -----> If (T> = strlen (msg2)... // right
The "error" we mentioned here does not mean a syntax error. All syntaxes are correct, and compilation and running are successful. The "error" here indicates that this statement cannot work as expected. The results of these four statements are always true.
Why?
Let's first look at the prototype of the library function strlen:
Size_t strlen (char const * string );
Note that strlen returns a value of Type size_t. What type is size_t? This type is defined in the header file stddef. H. It is an unsigned integer type. When the problem arises, the use of the unsigned number in the expression may lead to unpredictable consequences.
When there are signed and unsigned types in the expression, all operands are automatically converted to the unsigned type. The calculation result of the unsigned number cannot be negative. Therefore, the results of the four statements, 2, 4, 5, and 6, will always be true.
In this case, you either use the Form 1, 3, 7, or forcibly convert the strlen return value to int.
String type cannot use strlen () for length. strlen only applies to all char * types.
If required, first convert the string type to the char * type and use the c_str () function to convert it.
# Include <iostream>
# Include <string>
Using namespace STD;
Int main ()
{
String STR = "fjaljjfj ";
Int Len;
Len = strlen (Str. c_str ());
Cout <Len <Endl;
Return 0;
}