Question about strcmp

For example, we have two lines:

string s = "cat"; string s1 = "dog"; 

Is the following method correct?

 int a = strcmp(s, s1); 

Or what will be the correct form?

+4
source share
2 answers

C ++ std::string can be compared directly, so you can just write, for example.

 if (s == s1) cout << "the strings are equal" << endl; else if (s < s1) cout << "the first string is smaller" << endl; else ... 

But if you really need an integer value, you can use the .compare method .

 int a = s.compare(s1); 
+11
source

Just for completeness, while you should use the built-in string functions when possible, there are common situations where you often have to compare a C-style zero-terminated string with a C ++ string. For example, you will constantly encounter situations when a system call returns a pointer to a C-string.

You can include a C string in a C ++ string and compare them

 string s1 = "cat"; string s2 = "dog"; const char *s3 = "lion"; if (s1 == string(s3)) cout << "equal" << endl; else cout << "not equal" << endl; 

or compare a C-line under C ++ with another C-line:

 a = strcmp(s1.c_str(), s3); 
+1
source

Source: https://habr.com/ru/post/1315265/


All Articles