2016-10-22 104 views
-4

我正在使用用戶輸入的字符串輸入,我需要使用switch語句來評估每個輸入的輸入。我的下面的代碼當前評估用戶字符串輸入,並使用ASCII代碼查看它是大寫字母,數字還是特殊字符。我現在知道switch-statements如何工作,以及如何將If語句更改爲switch-statement。Switch語句評估字符串輸入C++

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 

任何意見或例子會幫助,謝謝。

+0

任何輸入或方向或鏈接會幫幫忙我沒有使用開關語句非常多,我我不是100%確定他們是如何工作的。 – jravager

+0

你真的應該讀[問]。 – dandan78

+0

@ dandan78第一次發佈任務,我應該改變什麼才能讓它變得更好? – jravager

回答

0

如果性能比較沒有問題,我只是會用std::count_if

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

工作例如在ideone

+0

在這個例子中,算法庫是「isupper」的一部分嗎? – jravager

+0

我也可以爲特殊角色做類似的事情嗎? – jravager

+0

你可以在這裏找到所有功能http://en.cppreference.com/w/cpp/string/byte/isalpha – Slava