如何检查用户是否进行了两次相同的选择?

时间:2015-01-31 04:56:04

标签: c++

我有一个非常简单的程序,要求用户从列表中选择3个玩家。有没有办法阻止用户两次选择同一个播放器?最初,我有它,所以无论用户做什么选择都会被添加到std :: set然后我会检查该选择。然后我意识到这个想法是多么荒谬,因为选择总是会被添加到集合中。

   #include <iostream>
   #include <string>

int main()
{
int m_NumOfPlayers;

std::string m_PlayerSelection [6] = 
{ 
    "Miss Scarlet",
    "Mrs. Peacock", 
    "Colonel Mustard",
    "Professor Plum",
    "Mrs. White", 
    "Mr. Green" 
};

std::string m_Number [6] = 
{ 
    "first", 
    "second", 
    "third",
    "fourth", 
    "fifth", 
    "sixth" 
};

for (int i = 0; i < 3; i++)
{
    std::cout << "\nPlease choose the " << m_Number[i] << " player" << ":" << std::endl << std::endl;
    for (int j = 0; j < 6; j++)
    {
        std::cout << (j + 1) << ". " << m_PlayerSelection[j] << std::endl;
    }

    int selection;
    std::cin >> selection;

    while (selection < 1 || selection > 6)
    {
        std::cout << "Please choose a number between 1 and 6: ";
        std::cin >> selection;
    }
}
system("pause");
return 0;
}

2 个答案:

答案 0 :(得分:0)

可能有很多方法,但我还是新的,所以我要做的是将数据结构更改为vector。这样你就可以推出或推出。

#include <vector> //Necessary if you are not familiar with vectors.
#include <iostream>
using namespace std;
int main(){
    vector<string> names;
    names.push_back("Miss Scarlet");
    names.push_back("Mrs. Peacock");
    //...Keep going
    for(int i=0; i<3; i++){
        string temp;
        cout<<"Select";
        cin>>temp;
        names.erase(find(vector.begin(), vector.end(), temp)!=vector.end());
    }
}

像我这样的东西我不是巫师,但希望它足够了。

答案 1 :(得分:0)

您可以使用:

#include <iostream>
#include <string>
#include <iomanip>

int main()
{
    int m_NumOfPlayers;

    std::string m_PlayerSelection [6] =
    {
        "Miss Scarlet",
        "Mrs. Peacock",
        "Colonel Mustard",
        "Professor Plum",
        "Mrs. White",
        "Mr. Green"
    };

    std::string m_Number [6] =
    {
        "first",
        "second",
        "third",
        "fourth",
        "fifth",
        "sixth"
    };

    int taken[7]={0,0,0,0,0,0,0};// Array to keep track of the selected names

    for (int i = 0; i < 3; i++)
    {
        std::cout << "\nPlease choose the " << m_Number[i] << " player" << ":" << std::endl << std::endl;
        for (int j = 0; j < 6; j++)
        {
            std::cout << (j + 1) << ". " << m_PlayerSelection[j] ;

            // printing if the name is already taken by someone
            if(taken[j+1] == 1)
            {
                std::cout << std::setw(10);
                std::cout << "-- taken" << std::endl;
            }
            else
              std::cout << std::endl;
        }

        int selection;
        std::cin >> selection;

        while (selection < 1 || selection > 6 || taken[selection])
        {
            std::cout << "Please choose a number between 1 and 6 which is not taken already: ";
            std::cin >> selection;
        }
        taken[selection]=1; // mark selected name
    }
    return 0;
}