检查用户输入是否等于数组元素

时间:2019-04-11 20:27:21

标签: c++

我有一个包含多个名称的字符串数组。 我想使用if语句检查用户输入是否等于任何名称。

例如:

names[5] = {'david','rares','tudor','john','jay'}

cin>>name;

现在我想检查名称是否等于数组中的任何元素。

非常不好的例子:

if(name == names) 
{
cout<<"you can use this name. Name: "<<name;
}

3 个答案:

答案 0 :(得分:0)

如user4581301所指出,'david'不是字符串,而是多字节字符(而且也很可能不是有效的字符)。如果要保留一组名称并检查其中是否存在某些名称,则可以使用std::setstd::unordered_set而不是数组。示例:

#include <iostream>
#include <set>
#include <string>

int main() {
    std::set<std::string> names = {"david", "rares", "tudor", "john", "jay"};
    std::string name;

    std::cin >> name;
    if(names.count(name)) // or names.contains(name) in C++20
        std::cout << "found\n";
    else
        std::cout << "not found\n";
}

答案 1 :(得分:0)

您可以执行以下操作:

#include <iostream>
#include <algorithm>

int main()
{
    const char * v [] = { "david", "rares", "tudor", "john", "jay" };
    std::string name;
    std::cin >> name;
    auto result = std::find (std::begin (v), std::end (v), name);
    if (result != std::end (v))
        std::cout << name << " is valid\n";
}

尽管请注意,大多数人会使用std::vector <std::string>来保存字符串列表。

Live demo

答案 2 :(得分:0)

我建议使用向量存储名称,以便您知道大小。如果必须使用静态数组,请确保保存当前大小并在删除/添加名称时进行更新。

某人可能有更有效的解决方案,但是您可以使用for循环线性搜索数组。

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    string names[5] = {"david","rares","tudor","john","jay"};
    cout << "Enter name: ";
    cin >> name;

    for (int i = 0; i < 5; i++)
    {
        if(names[i] == name)
        {
            cout << name << " was found in the array." << endl;
            return 0;
        }
    }

    cout << name << " wasn't found in the array." << endl;
    return 0;
}

此解决方案不适用于区分大小写的名称(David和david被认为是两个单独的名称)。