Switch语句对输入的字符串求值

Switch statement to evaluate string input C++

本文关键字:字符串 输入 语句 Switch      更新时间:2023-10-16

我正在处理用户输入的字符串输入,我需要使用开关语句来计算每个输入的输入。下面的代码当前计算用户字符串输入,并使用ASCII码查看它是大写字母、数字还是特殊字符。我现在确定了switch语句是如何工作的,以及如何将If语句更改为switch语句。

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

任何建议或例子都会有所帮助,谢谢。

如果性能不是问题,我就使用std::count_if:

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

ideone的工作示例