jravager jravager - 1 month ago 17
C++ Question

Switch statement to evaluate string input C++

I am working with a user entered string input and I need to use switch-statements to evaluate each of the entered input. My code below currently evaluates a users string input and looks to see if it is a upper case, number, or special character using ASCII codes. I am now sure how switch-statements work and how I could change an If statement to a switch-statement.

for (int i = 0; i < strlength; i++) //for loop used to check the rules of the password inputted by the user
{
cout << "Testing for upper case characters..." << endl; //displays the cout
tmpi=(int) str1[i]; //stoi function making the string input an integer
if ((tmpi >= 65) && (tmpi <= 90)) //checks if there are two upper case characters in the string
{
cout << "Found an uppercase" << endl;
uppercnt++; //adds to the counter of upper case
state++;
cout << "Now in state q" << state << "..." << endl;
continue;
}
cout << "Testing for digits..." << endl;
if(tmpi >= 48 && tmpi <= 57) //checks if there are two digits in the string
{
cout << "Found a digit" << endl;
digitcnt++; //adds to the counter of digit
state++;
cout << "Now in state q" << state << "..." << endl;
continue;
}
cout << "Testing for special characters..." << endl;
if(tmpi >= 33 && tmpi <= 47 || tmpi >= 58 && tmpi <= 64 || tmpi >= 91 && tmpi <= 96 || tmpi >= 123 && tmpi <= 126) //checks if there are special characters
{
cout << "Found a special char" << endl;
speccnt++; //adds to the counter of special character
state++;
cout << "Now in state q" << state << "..." << endl;
continue;
}
cout << "Character entered was a lower case" << endl;
state++;
cout << "Now in state q" << state << "..." << endl;
} //end for loop


Any advice or examples would help out, thanks.

Answer

if perfomance not an issue, I just would use std::count_if:

int upps = std::count_if( pass.begin(), pass.end(), isupper );
int digs = std::count_if( pass.begin(), pass.end(), isdigit );

working example on ideone