Home > Software engineering >  Is there a way to write the following python If statement condition in C ?
Is there a way to write the following python If statement condition in C ?

Time:11-30

Im in the process of trying to recreate a piece of python code for a simple calculator in C ,

in python i have the following piece of code thats located in a while loop

func = str(input("which function: add, sub, div, mult"))
if func in ("add", "sub", "div", "mult"):
   #secondery if statment

else:
   print("error")

how would i go about writing if func in ("add", "sub", "div", "mult"): in C ?

i have tried

if (func in {"add", "sub", "div", "mult"}){                
    //secondery if statment

else:
   std::cout << "error \n";

}

but this doesn't work.

CodePudding user response:

C 17 shorthand version:

template<typename T, typename... Args>
[[nodiscard]] constexpr bool isAnyOf(T&& a, Args&&... args) noexcept
{
    return ((a == args) || ...);
}

There is also C 11 std::any_of

CodePudding user response:

Here's a working snippet

#include <iostream> // std::cout, std::cin
#include <string>
#include <array> // one of the many STL containers
#include <algorithm> // std::find

int main() {
    const std::array<std::string, 4> functions = { 
        "add",
        "sub",
        "div",
        "mult"
    };

    std::string user_input;
    std::cout << "which function: add, sub, div, mult? ";
    std::cin >> user_input;

    if (std::find(functions.begin(), functions.end(), user_input) != functions.end()) {
        std::cout << "found" << std::endl;
    } else {
        std::cout << "not found" << std::endl;
    }
}

If you want to dig more into Python's in operator equivalents there's this question with a great answer.

NOTE: If you want to know which string was found you should store the iterator returned by std::find() and dereference it when needed.

  • Related