Home > Software design >  How to check whether an element exists in an array as in Python using "in"
How to check whether an element exists in an array as in Python using "in"

Time:10-17

A user has to select a choice from the menu, and the program's goal is to check whether the user has selected a valid choice or not. In python I would run a while loop and compare them using "in": (userChoice in validChoices). How do I do that in C using a while loop?

Valid choices are stored in this variable:

const char validChoices[12] = {'P', 'p', 'A', 'a', 'M', 'm', 'S', 's', 'L', 'l', 'Q', 'q'}

The program asks the user for input and stores it in a char variable:

char userChoice {};
std::cin >> userChoice;

If the choice is invalid, the program should say "Unknown selection, please try again" and ask again for the input until the user selects a valid option.

Appreciate the help in advance!! Been struggling with it a lot.

Current attempt:

bool isValidChoice = true;


while (isValidChoice)
{
    char userChoice {};
    std::cout << "Select a choice: ";
    std::cin >> userChoice;

    if ()
    {
        std::cout << "You have selected: " << userChoice << std::endl;
        isValidChoice = false;
    }
    else
    {
        std::cout << "Unknown selection, please try again" << std::endl;
    }

CodePudding user response:

You can simply call

auto it = std::find(std::begin(validChoices), std::end(validChoices), userChoice);

by checking statement

if(it != validChoices.end())

it means that your choice have been found in the validChoices, because userChoice value have been found before validChoices end structure iterator. If it would be validChoices.end() that would mean that it just couldn't be found.

CodePudding user response:

There are many ways to solve this issue without having to write a while loop.

One way is to store the valid input in a string, and search the string using strchr:

#include <cstring>
#include <iostream>

bool isValidChoice(char ch)
{
   const char *validChoices = "PpAaMmSsLlQq";
   return strchr(validChoices, ch);
}
 
int main()
{
   std::cout << isValidChoice('P') << "\n";   
   std::cout << isValidChoice('s') << "\n";   
   std::cout << isValidChoice('Y') << "\n";   
}

Output:

1
1
0
  • Related