check string

#include <iostream>
#include <string>
using namespace std;
void check(const string& s1,
const string& s2) {
if (s1 == s2) cout << "== ";
if (s1 != s2) cout << "!= ";
if (s1 <= s2) cout << "<= ";
if (s1 >= s2) cout << ">= ";
if (s1 < s2) cout << "< ";
if (s1 > s2) cout << "> ";
cout << endl;
}
int main()
{
string s1 = "Earth";
string s2 = "Earth";
string s3 = "Mars";
string s4 = "Jupiter";
check(s1,s2);
check(s2,s3);
check(s3,s4);
}
Output:
== <= >=
!= <= <
!= >= >


i dun understand y thr is 3 output for each comparation?

Well, that's exactly what your program is expected to do.

Let's take a closer look at check(s1,s2);:

s1==s2 is true, because s1 is equal to s2 (they both are "Earth"), thus "==" is printed.

s1!=s2 is false, thus nothing is printed

s1<=s2 is true, because ( (s1<s2) or (s1==s2) ) is true, because s1 is equal to s2, thus "<=" is printed.

s1>=s2 is true, because ( (s1>s2) or (s1==s2) ) is true, because s1 is equal to s2, thus "<=" is printed.

s1<s2 is false, thus nothing is printed

s1>s2 is false, thus nothing is printed

If you want it to print only one result for each comparison, your check function should look like this:

1
2
3
4
5
6
7
8
void check(const string& s1, const string& s2)
{
    if (s1 == s2) cout << "== ";
    else if (s1 < s2) cout << "< ";
    else cout << "> ";

    cout << endl;
}
because if s1 == s2 is true, also s1 <= s2 and s1 >= s2 will be true
ok.thanks u:)
Topic archived. No new replies allowed.