I'm trying to declare this string as Invalid
but in an input like this:
59G71341
or 8pjf7h14sx13
or 60s1v344
My output is getting approved through my string if statement and is getting listed as Valid
.
Could anyone guide me to why its passing through my if statement and labeling Valid
!!
I haven't learned how to use a debugger yet so bare with me.
Task description:
Declare a Boolean variable named goodPasswd. Use goodPasswd to output "Valid" if secretStr contains no more than 5 digits and secretStr's length is greater than or equal to 5, and "Invalid" otherwise.
Ex: If the input is 80796, then the output is: Valid
Ex: If the input is XBdg, then the output is: Invalid
#include <iostream>
using namespace std;
int main()
{
string secretStr;
bool goodPasswd = false;
cin >> secretStr;
int counter = 0;
for (int i = 0; i < secretStr.length(); i)
{
if ((secretStr[i] >= 0) && (secretStr[i] <= 9))
{
counter;
}
} //approves string if both true
if ((counter <= 5) && (secretStr.length() >= 5))
{
goodPasswd = true;
}
else
{
goodPasswd = false;
}
if (goodPasswd)
{
cout << "Valid" << endl;
}
else
{
cout << "Invalid" << endl;
}
return 0;
}
CodePudding user response:
if ((secretStr[i] >= 0) && (secretStr[i] <= 9))
should be
if ((secretStr[i] >= '0') && (secretStr[i] <= '9'))
0
and 9
are integers, but you are comparing characters, so you need to use the characters '0'
and '9
', or you could just use the isdigit
function.
if (isdigit(secretStr[i]))
isdigit
is declared in #include <cctype>
Not related to your question but you don't need to goodPasswd
variable. Simply
if (counter <= 5 && secretStr.length() >= 5)
{
cout << "Valid" << endl;
}
else
{
cout << "Invalid" << endl;
}
seems a bit cleaner to me.