Unexpected behaviour of c++ string::compare() fn

Viewed 68

The string::compare() has one of its overloaded forms as

int compare (size_t pos, size_t len, const string& str) const;

Now consider following 2 scenarios:

Scenario 1:

string s1="steven", s2="steve";
cout<<s1.compare(0, 5,s2);

Scenario 2:

string s1="steven", s2="stevec";
cout<<s1.compare(0, 5,s2);

The O/P in first case is 0(expected) but in 2nd case yields -1(unexpected). The fn call translates to compare first 5 chars of s1 to those of s2.So, how come the output is getting affected by 6th char of s2.Can someone please care to explain the reason behind such implementation of a standard library fn.

1 Answers

As described in cppreference:

  1. Compares a [pos1, pos1+count1) substring of this string to str. If count1 > size() - pos1 the substring is [pos1, size()).

Nothing is said about the second string size. It means that the whole string2 is compared. So everything's as expected.

Related