2014-07-19 68 views
0

我正在尋找一種方法來檢查用戶輸入的字符串,當提示(讓我們把它看作是一個字符串變量「userinput」)從其他10個字符串的數組中。到目前爲止,我有:檢查字符串是否與字符串數組中的任何字符串匹配?

while (userinput.empty()) //Check for empty input 
{ 
    cout << "Please enter your identity.\n"; //Identify user 
    getline(cin, userinput); 

    do //Check to see if user is the same as the string variable "user" 
    { 
    cout << "This user is either non existent or has access privileges revoked.\n"; //Wrong username! 
    cout << "Please re-enter the username.\n"; 
    getline(cin, userinput); 
    } 
    while (user != userinput); 
} 

可以看出,雖然這隻適用於單個字符串變量「用戶」。我將如何改變這個字符串數組?

數組本身是:

string arr[10] = {"Test1", "Test2", "Test3", "Test4", "Test5", "Test6", "Test7", "Test8", "Test9", "Test10"}; 

請注意:我不打算使用的密碼,只有用戶名。

+0

寫一個單獨的函數返回一個'bool',即在一個循環中檢查'userinput'參數通過該陣列和去在你的'while()'中使用這個作爲條件。 –

+0

嗨,我對C++沒有經驗,你能否擴展你的建議? – Talisman

+0

我寫了一個答案。我希望你明白這個主意。 –

回答

2

放在一個單獨的功能

bool isValidUserName(const string& input) { 
     for(int i = 0; i < 10; ++i) { 
      if(input == arr[i]) { 
       return true; 
      } 
     } 
     return false; 
} 

檢查,並在同時使用它作爲條件

while (!isValidUserName(userinput)); 
+0

謝謝你。它似乎只驗證數組的第一個元素,並在第一個之後拒絕任何其他用戶名? – Talisman

+0

@HarryLudlow不,它將數組中的每個元素與給定的輸入參數進行比較。 –

+0

奇怪。它只接受Test1而不接受Test2(或任何其他),但是當我在數組中交換時,只有測試2工作。 – Talisman

3

您可以使用內置的count功能,像這樣:

do{ 
    getline(cin, userinput); 
} 
while(!std::count(arr, arr+10, userinput)); 

也在ideone

這是你的循環應該是什麼樣子:

cout << "Please enter your identity.\n"; //Identify user 
getline(cin, userinput); 
while (!std::count(arr, arr+10, userinput)) //Check to see if user is the same as the string variable "user" 
{ 
    cout << "This user is either non existent or has access privileges revoked.\n"; //Wrong username! 
    cout << "Please re-enter the username.\n"; 
    getline(cin, userinput); 
} 

你可以看到它here

+0

我得到一個'數'不是'std'的成員 - 我使用命名空間標準,如果有幫助? – Talisman

+1

你可能忘了'#include '(只需點擊ideone鏈接):)(順便說一句,使用'namespace std;'是[不推薦](http://stackoverflow.com/questions/1452721)。) – Scis

+0

啊,那會解釋它!對不起,剛剛掌握C++。是的,我知道使用它並不是一個好主意,但是一旦我解決了這個問題,我就會改變它:D – Talisman

1

如果您有大量字符串進行比較,那麼使用哈希映射(std::unordered_set)而不是數組會更高效。在一個哈希表中搜索比在一個數組中快得多。

unordered_set<string> valid_inputs {"Test1", "Test2", "Test3", "Test4", "Test5", "Test6"}; 

然後就可以檢查用戶輸入以這樣的方式:

if (valid_inputs.find(user_input) == valid_inputs.end()) 
    cout << "error"; 
else 
    cout << "success"; 
+0

謝謝你。我會嘗試我認爲的兩種方法,並感受不同的方法! – Talisman

相關問題