How to check which argument was picked from a given prompt ?

template <class choice>
choice GetChoice(string leftStr, string rightStr, choice a , choice b)
{

cout << "Please pick " << leftStr <<" or " << rightStr;
if()
{

}

}

Im trying to figure out a way where I can check if the leftStr was picked I can return choice a or rightStr was picked so I can return choice b.

for example:
If I were to call GetChoice("seven", "eleven", 7, 11)
the user should see something like:
Please pick seven or eleven:
If they (eventually) enter "seven", the function should return the integer value 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
string userInput; // Variable to store user input

cout << "Please pick " << leftStr <<" or " << rightStr;

cin >> userInput // Get user input

if(userInput == leftStr) // Check if what the user wrote is equal to leftStr
{
   // return something
}
else if(userInput == rightStr) // Check if what the user wrote is equal to rightStr
{
   // return something else
}


That's that. But ask yourself the question. What happens if the user chooses neither of the options, and types "football" instead? Need to write something to handle that, using some kind of loop :)
closed account (z05DSL3A)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <limits>


template <class choice>
choice GetChoice (std::string leftStr, std::string rightStr, choice a, choice b)
{
    std::string input{};
    while ((std::cout << "Please pick " << leftStr << " or " << rightStr << "\n")
        && (!(std::cin >> input) || (input != leftStr && input != rightStr)))
    {
        std::cout << input << " is not a valid option.\n";
        std::cin.clear ();
        std::cin.ignore (std::numeric_limits<std::streamsize>::max (), '\n');
    }
    return input == leftStr ? a : b;
}

int main () 
{
    int x = GetChoice ("seven", "eleven", 7, 11);

    std::cout << x << "\n\n";

    return 0;
}
Please pick seven or eleven
football
football is not a valid option.
Please pick seven or eleven
seven
7
Last edited on
Topic archived. No new replies allowed.