我正在做一些 C ,我的應用程式接受子命令,例如./my_app test 123.
我是 C 的新手,我在互聯網上找不到任何東西,所以我不知道哈哈。
例如在python中我會這樣做:
#!/usr/bin/env python3
import sys
def test(num):
print(f"Test {num}")
subcommands = {"test": test}
subcommands[sys.argv[1](sys.argv[2])
任何 C eq 到這個?如果是這樣,我應該使用它還是堅持使用 if-else_if-else?
uj5u.com熱心網友回復:
看看std::map/ std::unordered_map,例如:
#include <iostream>
#include <map>
#include <string>
void test(const std::string &value) {
std::cout << "Test " << value << std::endl;
}
using cmdFuncType = void(*)(const std::string &);
const std::map<std::string, cmdFuncType> subcommands = {
{"test": &test}
};
int main(int argc, char* argv[]) {
if (argc != 3) {
std::cerr << "usage: program command value" << std::endl;
return 0;
}
auto iter = subcommands.find(argv[1]);
if (iter == subcommands.end()) {
std::cerr << "unknown command: " << argv[1] << std::endl;
return 0;
}
iter->second(argv[2]);
return 0;
}
uj5u.com熱心網友回復:
這是您要實作的目標嗎:
#include <string>
#include <functional>
#include <iostream>
#include <map>
void test(int num) {
std::cout << "Test " << num << "\n";
}
std::map<std::string, std::function<void(int)>> subcommands = {
{"test", test}
};
int main(int argc, char* argv[]) {
subcommands[argv[1]](std::atoi(argv[2]));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/330386.html
