Reputation: 443
I have a problem with this code, I'm trying to verify if a letter is in a word, but for some reasons it won't allow me to put ==
.
#include <string>
#include <iostream>
using namespace std;
bool Verification(string a, string b)
{
bool VF = false;
for (int i = 0; i < a.size(); i++)
{
if (a[i] == b) //Here is the problem
{
VF = true;
}
}
return VF;
}
Upvotes: 0
Views: 608
Reputation: 34189
a
is a string and b
is a string.
a[i]
is a char
. You compare char
to string
- obviously, it will not work.
If you want to check if a letter (i.e. char
) exists in a sentence (i.e. string
), you can implement the function this way:
bool Verification(string a, char b) // <-- notice: b is char
{
bool VF = false;
for (int i = 0; i < a.size(); i++)
{
if (a[i] == b)
{
VF = true;
}
}
return VF;
}
// Usage:
Verification("abc", 'a'); // <-- notice: quotes are double for string and single for char
Actually, there is a method string::find
, which can help you to find an occurence of string
or char
in another string
You can replace your code with:
#include <string>
#include <iostream>
using namespace std;
bool Verification(string a, char b)
{
return a.find(b) != string::npos;
}
Upvotes: 4