mardi 16 mars 2021

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

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.

Aucun commentaire:

Enregistrer un commentaire