I have a simple program that asks the user to select 3 players from a list. Is there any way to keep the user from selecting the same player twice? I tried creating an std::set to remember all the numbers and check for duplicates, but I'm pretty sure I implemented it wrong as I don't really know what std::sets are or how they even work.
#include <iostream>
#include <string>
#include <set>
int main()
{
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 players = 0;
std::set<int> numbers; //You need set to stay persistent between iterations
while (players < 3) {
std::cout << "\nPlease choose the " << m_Number[players] << " player:\n\n";
for (int j = 0; j < 6; j++)
std::cout << (j + 1) << ". " << m_PlayerSelection[j] << '\n';
//We need to get proper number before checking it against set
int selection;
do {
std::cout << "Please choose a number between 1 and 6: ";
std::cin >> selection;
} while (selection < 1 || selection > 6);
if (numbers.find(selection) != numbers.end()){//find retirns end iterator if nothing was found
std::cout << "That selection has already been made\n";
continue; //Restart input again
} else {
numbers.insert(selection);
++players;
}
}
}
Another solution is to remove already taken characters from choosing altogether.