检查字符串匹配字符串数组的字符串? [英] Checking a string matches any string in a string array?

查看:174
本文介绍了检查字符串匹配字符串数组的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一种方法来检查字符串,用户输入的提示时,(让我们它是一个字符串变量userinput),从其他10个字符串数组。到目前为止,我有:

I'm looking for a way to check a string that a user inputs when prompted (let's take it to be a string variable "userinput") from an array of 10 other strings. So far I have:

    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);
}

可以看出,虽然,这只能用于一个字符串变量用户。我将如何改变这种为一个字符串数组?

It can be seen though, that this only works for a single string variable "user". How would I change this for a string array?

该阵列本身如下:

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

请注意:我不打算使用的密码,用户名只能

Please note: I'm not intending to use passwords, only usernames.

推荐答案

把支票在一个单独的函数

Put the check in a separate function

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

和在同时使用它作为条件

and use it as condition in the while

 while (!isValidUserName(userinput));

这篇关于检查字符串匹配字符串数组的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆