检查字符串是否与字符串数组中的任何字符串匹配
Checking a string matches any string in a string array?
我正在寻找一种方法来检查用户在提示时输入的字符串(让它是一个字符串变量"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);
}
可以看到,这只适用于单个字符串变量"user"。对于字符串数组,我该如何改变它呢?
数组本身如下:
string arr[10] = {"Test1", "Test2", "Test3", "Test4", "Test5", "Test6", "Test7", "Test8", "Test9", "Test10"};
请注意:我不打算使用密码,只使用用户名。
您可以这样使用内置的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);
}
你可以在这里看到
将检查放在单独的函数中
bool isValidUserName(const string& input) {
for(int i = 0; i < 10; ++i) {
if(input == arr[i]) {
return true;
}
}
return false;
}
并将其用作while
中的条件 while (!isValidUserName(userinput));
如果您有大量字符串要比较,那么使用哈希映射(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";
相关文章:
- 删除字符串中具有相同值的任何相邻字母"pair"
- 在处理任何字符大小的模板中使用字符串文本
- 如何创建一个模板化函数,可以在任何具有字符串键的 std::map 上运行?
- 为什么字符串没有更新并且最终没有打印任何内容
- 是否可以对任何语句字符串使用预准备语句?
- 如何在不进行任何其他修改的情况下"pretty print" C++的XML字符串?
- 如何将csv中的数据放入c++中的字符串向量中,而绝对没有任何作用
- 当我在将文件读取到C字符串的2D数组后尝试对任何内容进行定制时,C++分段错误
- 是否可以用类似C/C++(或任何语言)的语言,从作为用户输入的字符串或文件中创建用户定义的数据类型
- 当通过常量和不是字符串的最佳选择时,是否有任何情况?
- 构造字符串向量时是否有任何副本?
- C++ 复制字符串的指定索引之间的任何子字符串
- Cout 一个字符串可以打印任何内容到屏幕上
- 查找字符串是否包含字符串向量的任何一个元素的最佳方法
- 有人知道可以使用 c++ 以字节为单位编码 asm 字符串的任何东西吗?
- 我想知道如何将所有数值与没有任何空格的字符串分开,就像 123we45rt75 一样
- 字符串流在清除后不接受任何数据
- 任何C 字符串库,例如QString(或Java String)
- 除了字符串或宏调用之外,是否存在任何情况,其中"(<"是有效的字符流?
- 带有 std::的任何值unordered_map不能any_cast字符串