2014-07-19 67 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

相关问题