I was just doing a simple coding challenge for c++ as I am relatively new to the language, I wanted to compare two strings to each other lexicographically, so as to print out 1 if the first string entered was lexicographically bigger than the second one, and to print out -1 if the opposite was true. As I was looping, I wanted to only compare them equally in lower case, so if a character from the first string was a capital "A" I wanted to turn it into a lower case "a", and that same rule applied to every character for both strings that were being compared. When I tried to implement that idea in my if
statement using the <cctype>
header like so... first_str[i].tolower()
and the same for the second string, I got the error "expression must have class type". Here is my code:
#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;
}
I decided to investigate a little further but to no avail, like I said I am a beginner in C++, when I came across people with a similar compilation error, the answers would talk about things called pointers...that I haven't learnt yet and so was very confused. I want to know if I need to learn that to understand why this is happening or is there another reason to why this problem is occurring in my code. I will try my best to learn about pointers soon enough, and thank you for reading my problem.