Home > Software engineering >  How to call a function by its name (will be changed by user input) in C ?
How to call a function by its name (will be changed by user input) in C ?

Time:12-12

I wonder if there is a way to call a function from user's input. I tried fixed typing directly, but want to make it different by user's input.

If I have functions like this ->

int Step001();
int Step002();

I want to use it by just typing numbers

[output]
type step number > 
[input]
1
> calling function by {"step00" (user input number)}

CodePudding user response:

I'd build a key value store pointing strings to functions.

#include <cassert>
#include <functional>
#include <iostream>
#include <map>

static int Step001() { 
  std::cout << "a\n";
  return 1;
}

static int Step002() {
  std::cout << "b\n";
  return 2;
}


int main() {
  static const std::map<std::string, std::function<int()>> functions = {
    {"step001", &Step001},
    {"step002", &Step002},
  };

  // Get user input
  int StepNumber = 1;

  // Lookup the function and call it.
  auto kv = functions.find("step00"   std::to_string(StepNumber));
  assert(kv != functions.end());
  auto &function = kv->second;
  function();
}
  • Related