我想知道是否有辦法從用戶的輸入中呼叫函式。我嘗試直接固定輸入,但希望通過用戶輸入使其不同。
如果我有這樣的功能 - >
int Step001();
int Step002();
我想通過輸入數字來使用它
[output]
type step number >
[input]
1
> calling function by {"step00" (user input number)}
uj5u.com熱心網友回復:
我會建立一個鍵值存盤,將字串指向函式。
#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();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/384331.html
