gpt4 book ai didi

c++ - 比较模板中的两个字符串

转载 作者:行者123 更新时间:2023-11-28 06:52:10 26 4
gpt4 key购买 nike

当我测试整数、 double 和字符时。它工作正常。只有字符串在使用相同模板时有问题。我没有在此处包含 int、float 和 char 的代码。

#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;
}

结果

1)Enter two strings you want to compare.twotwotwo2)Enter two strings you want to compare.two threethree twothree two3)Enter two strings you want to compare.abcdef gabcdef ghiabcdef ghi

对于结果 #1,我不明白为什么“two”和“two”会返回“two”而不是显示“他们都一样”的消息。

对于结果#2,“二三”不是和“三二”一样吗?我不明白“三二”怎么变小了。

对于结果 #3,该程序似乎只会返回测试 2。

最佳答案

当两者相等时,您缺少 return 语句。

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;
}

你说:

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

这确实很奇怪。可能输入中有空白字符。

你说:

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

字符串“二三”与“三二”不同。 “三二”较小,因为如果您必须将这些字符串放入字典中,“三二”将排在“二三”之前。

你说:

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

这很奇怪。

事实证明,我在测试中看到的行为与您在测试中看到的相同。罪魁祸首竟然是这条线:

cin.ignore();

在我删除该行后,代码的行为与您预期的一样。

关于c++ - 比较模板中的两个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23746325/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com