user3347541
user3347541

Reputation: 27

Comparing two strings in Template

When I test with ints, doubles, and char. It works fine. Only string haves problem using the same template. I have not included the code for int, floats and chars here.

#include <iostream>

using namespace std;

template <class T>
T minimum (T test1, T test2)
{
    if(test1 > test2)
        return test2;
    if(test2 > test1)
        return test1;

    cout << "They're both the same." << endl;
}

int main()
{
string str1, str2;
string temp;
    cout << "Enter two strings you want to compare." << endl;
    cin.ignore();
    getline(cin, str1);
    getline(cin, str2);

    temp = minimum(str1, str2);
    cout << temp;
return 0;
}

RESULTS

1)
Enter two strings you want to compare.
two
two
two

2)
Enter two strings you want to compare.
two three
three two
three two

3)
Enter two strings you want to compare.
abcdef g
abcdef ghi
abcdef ghi

For result #1, I don't understand why "two" and "two" will return "two" instead of bringing out the message "They're both the same."

For result #2, isn't "two three" the same as "three two"? I don't understand how "three two" is smaller.

For result #3, it seems like this program is only going to return test 2.

Upvotes: 0

Views: 250

Answers (1)

R Sahu
R Sahu

Reputation: 206617

You are missing the return statement when the two are equal.

template <class T>
T minimum (T test1, T test2)
{
    if(test1 > test2)
        return test2;
    if(test2 > test1)
        return test1;

    cout << "They're both the same." << endl;
    return test1;
}

You said:

I don't understand why "two" and "two" will return "two" instead of bringing out the message "They're both the same."

That is strange, indeed. Perhaps there were whitespace characters in the input.

You said:

isn't "two three" the same as "three two"? I don't understand how "three two" is smaller.

The string "two three" is not the same as "three two". "three two" is smaller because if you had to put those strings in a dictionary, "three two" will come before "two three".

You said:

it seems like this program is only going to return test 2.

That is strange.

It turns out that I saw the same behavior in my tests that you saw in yours. The culprit turned out to be the line:

cin.ignore();

After I removed that line, the code behaved like you'd expect it to.

Upvotes: 1

Related Questions