Home > database >  C function to check whether value exists in tuple
C function to check whether value exists in tuple

Time:06-16

I'm a total beginner to C , and I am trying to code a program that checks user input to make sure it is a valid option.

Here's my code so far:

#include <iostream>
#include <string>
#include <tuple>

int UserInputCheck() {
    int x;
    cout << "Options: 1,2,3 or q. \n \n Choose an option:";
    cin >> x;
    tuple<int,int,int,string> valid_options{ 1, 2, 3, "q"};
    do {
        cout << "\nInvalid input. Please try again.";
        cin >> x;
    }
    while (x is not in valid_options); // This is psuedo-code, I'm looking for a function that does this
    
    cout << x << "\n";
    return 0;
{

So is there a C function that would check if x is in valid_options?

If not, how can I write one?

CodePudding user response:

static inline bool isValid(int input) {
        static const std::vector<int> valids = {1, 2, 3};

        return std::any_of(valids.begin(), valids.end(),
                                 [&input](const auto &s) { return input == s; });
    }

This function can do the coffee

EDIT: String version

static inline bool isValid(const std::string &input) {
static const std::vector<std::string> valids = {"1", "2", "3", "q"};

        return std::any_of(valids.begin(), valids.end(),
                                 [&input](const auto &s) { return input.find(s) != std::string::npos; });
}
  •  Tags:  
  • c
  • Related