"expression must have class type"但是在检查类型时,它确实有一类字符?



我只是在为c++做一个简单的编码挑战,因为我对这门语言相对陌生,我想用字典法将两个字符串相互比较,如果输入的第一个字符串在字典上比第二个字符串大,就打印出1,如果相反,就打印出来-1。当我循环时,我只想用小写对它们进行相等的比较,所以如果第一个字符串中的一个字符是大写的";A";我想把它变成小写";a";,同样的规则适用于被比较的两个字符串的每个字符。当我试图在if语句中使用<cctype>头来实现这个想法时,比如…first_str[i].tolower(),第二个字符串也是如此,我得到了错误";表达式必须具有类类型";。这是我的代码:

#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
int first{};
int second{};
string first_str{};
string second_str{};
cin >> first_str;
cin >> second_str;

for (size_t i{}; i < first_str.length(); ++i) {
// The if statement below has one accessing the character by indexing with the square brackets
// and the other one has it through the .at() method provided by the <string> header
if (first_str[i].tolower() > second_str.at(i).tolower()) {
++first;
} else if (first_str.at(i).tolower() < second_str.at(i).tolower()) {
++second;
} else { // If they are equal then just add the count to both
++first;
++second;
}
}
if (first > second)
cout << 1 << endl;
else if (first > second)
cout << -1 << endl;
else
cout << 0 << endl;
return 0;
}

我决定进一步调查一下,但没有用,就像我说的我是C++的初学者一样,当我遇到有类似编译错误的人时,答案是关于指针的东西。。。我还没有学会,所以很困惑。我想知道我是否需要了解这一点,以理解为什么会发生这种情况,或者我的代码中出现这种问题的另一个原因是什么。我会尽我最大的努力尽快了解指针,感谢你阅读我的问题。

这是因为firstrongtr[i]是字符。Char没有.tolower()方法。

所以不是:

first_str[i].tolower()

您应该使用:

tolower(first_str[i])

相关内容

最新更新