user466534
user466534

Reputation:

Question about strcmp

For example we have two strings:

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

Is it correct to write the following method?

int a = strcmp(s, s1);

Or what will be correct form?

Upvotes: 4

Views: 212

Answers (2)

Duck
Duck

Reputation: 27572

Just for completeness, while you should use the built-in string functions when you can, there are common situations where you often need to compare a C-style null terminated string to a C++ string. For instance you will constantly run into situations where a system call returns a pointer to a C-string.

You can choose to turn the C-string into 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 the C++'s underlying C-string to the other C-string:

a = strcmp(s1.c_str(), s3);

Upvotes: 1

kennytm
kennytm

Reputation: 523724

C++'s std::string can be compared directly, so you could just write e.g.

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 the integer value, you could use the .compare method.

int a = s.compare(s1);

Upvotes: 11

Related Questions