I'm having some difficulty checking for specific chars within my string. The requirements of the function is to check to make sure that "All characters (except the first) are lower case, whitespace, or punctuation (only ‘;’ or ‘,’)" I also have to make sure that the last character within the C-String is either a ! or a .
Here's what I have.
bool isItSentence(const char* s)
{
int x = strlen(s);
for (int c = 0; s[c] != '\0'; c++)
{
if (!isupper(s[0])) return false;
if (isupper(s[c]) && c > 0) return false;
if (s[c] != ' ' && s[c] != ';' && s[c] != ',' && !islower(s[c])) return false;
}
if (s[x - 1] != '.' && s[x - 1] != '!') return false;
return true;
}
int main()
{
std::string str = "Smelly.";
std::cout << isItSentence(str.c_str()) << std::endl;
system("pause");
}
However, I keep getting that it's not a sentence, even when it should be. Any suggestions on how I can fix this?
The problem seems to be occurring because you are looping from index 0 and checking that the first character should be uppercase and in a later statement, you are again checking that it should be lowercase.
if (!isupper(s[0])) return false;
and later
if (s[c] != ' ' && s[c] != ';' && s[c] != ',' && !islower(s[c])) return false;
During the first iteration, when c equals 0, you are basically checking that the first character should neither be uppercase nor lowercase and you get false because one of these will always be false. The following code should do it.
bool isItSentence(const char* s)
{
int x = strlen(s);
if (!isupper(s[0])) return false;
if (s[x - 1] != '.' && s[x - 1] != '!') return false;
for (int c = 0; c < x - 1; c++)
{
if (isupper(s[c]) && c > 0) return false;
if (s[c] != ' ' && s[c] != ';' && s[c] != ',')
if(!islower(s[c]) && c!= 0)
return false;
}
return true;
}
int main()
{
std::string str = "Smelly.";
std::cout <<" This is "<<isItSentence(str.c_str()) << std::endl;
system("pause");
}
Hope it helps!!