I was tasked with writing a program in c++11 (though my example and code were made in 14) that takes a user inputted string and tells you how many lowercase vowels there are in the string. However, when I try to compare the ith value in a string to a char, I get an error message telling me that operand types (char and const char) are incompatible. The code for that looked like this:
std::string inWord;
int lowerVowels = 0;
std::cin >> inWord;
void searchString(std::string inWord, int& lowerVowels) {
for (int i = 0; i < inWord.length(); i++) {
if (inWord.at(i) == "a") {
std::cout << "lowercase vowel found!";
lowerVowels++;
}
}
}
So I tried declaring other strings like so:
std::string la = "a", le = "e", li = "i", lo = "o", lu = "u";
and made this absolute nightmare of a for loop inside my searchString function like this:
if (inWord.at(i) == la.at(0) || inWord.at(i) == le.at(0) ||
inWord.at(i) == li.at(0) || inWord.at(i) == lo.at(0) ||
inWord.at(i) == lu.at(0)) {
lowerVowels++;
}
Which worked, however I'm sure I'm missing an easier way here, because this felt ridiculous. If anyone can explain why the first try didn't work (or because it's kind of easy to assume why that happened) what I should've done instead (unless my solution is considered optimal, which I doubt) I'd love to hear it!
You can create a
std::setand use itsfindmember orcontains(in C++20) as shown below:Pre C++20
Note also that double quotes around like in
"a"represents a string literal. What you actually wanted was a character literal which is created using a single quote. This means that you're trying to compare a string literal("a") which decays to aconst char*to achar(inWord.at(i)) and hence the erroroperand types (char and const char*) are incompatible