C++实现,简单的命令行交互框架

目录


背景

在实际开发中,经常需要有对端测试程序,配合自己的程序,验证功能、逻辑等。面对繁杂、多变的需求,如果对端程序设计得不够灵活,则无法提升工作效率,如果能够与对端程序交互,通过命令行输入命令的方式完成测试验证,将大大提升工作效率,下面的示例程序是一个简单的命令行交互框架,各位小伙伴可以根据自己的需求添加命令即可,如果对你有帮助,请点赞、收藏,谢谢!

c++ 复制代码
#include <iostream>  
#include <string>  
#include <vector>  
#include <sstream>  
  
/* 假设的命令处理函数 */  
void commandHelp() {  
    std::cout << "Available commands:\n"  
              << "  help - Display this help message\n"  
              << "  echo <arg> - Echo the argument back to you\n"  
              << "  quit - Exit the program\n";  
}  
  
void commandEcho(const std::string& arg) {  
    std::cout << "Echo: " << arg << std::endl;  
}  
  
/* 主命令处理函数 */  
void processCommand(const std::string& command, const std::vector<std::string>& args) {  
    if (command == "help") {  
        commandHelp();  
    } else if (command == "echo") {  
        if (args.empty()) {  
            std::cout << "Error: 'echo' requires an argument\n";  
        } else {  
            commandEcho(args[0]);  
        }  
    } else if (command == "quit") {  
        std::cout << "Exiting the program...\n";  
        exit(0);  
    } else {  
        std::cout << "Unknown command: " << command << std::endl;  
    }  
}  
  
/* 解析命令行参数 */ 
std::vector<std::string> parseArguments(const std::string& line) {  
    std::istringstream iss(line);  
    std::string token;  
    std::vector<std::string> args;  
    while (std::getline(iss, token, ' ')) {  
        if (!token.empty()) {  
            args.push_back(token);  
        }  
    }  
    return args;  
}  
  
int main() {  
    std::string commandLine;  
    while (true) {  
        std::cout << "> ";  
        std::getline(std::cin, commandLine);  
  
        if (commandLine.empty()) {  
            continue;  
        }  
  
        std::vector<std::string> args = parseArguments(commandLine);  
        if (args.empty()) {  
            continue;  
        }  
  
        std::string command = args[0];  
        args.erase(args.begin()); /* 移除命令本身,只保留参数 */  
  
        processCommand(command, args);  
    }  
  
    return 0; /* 这行代码实际上永远不会被执行,因为我们在'quit'命令中调用了exit() */  
}
相关推荐
梦想的旅途233 分钟前
Python实现企业微信文本消息发送
开发语言·python·企业微信
大鹏说大话1 小时前
美业微信会员系统哪个好
开发语言
程序员与背包客_CoderZ2 小时前
高性能分布式KV存储引擎RocksDB入门与C/C++编码实战
c语言·开发语言·数据库·c++·分布式·分布式数据库·rocksdb
进击的_鹏2 小时前
从零开始的 Redis 学习
服务器·数据库·c++·redis·缓存
feixing_fx2 小时前
告别枯燥字体:Web 字体加载策略与 font-display 最佳实践
前端·css·前端框架·交互·css3
钱栈up2 小时前
Mac 开发机一键发版不用切环境:我这样改造了团队的后端部署脚本Maven编译卡住20分钟?我靠两步定位到2处隐蔽编译错误
开发语言·python·macos
william_yangshun2 小时前
【大模型部署实战】kimi-k3-in-c 中文版:用 176KB 纯 C99 引擎在 CPU 上跑 Kimi K3 上手指南
c语言·开发语言
Sagittarius_A*2 小时前
Burst Lab | PHP 审计 14|反序列化(四):字符串逃逸与绕过技巧
开发语言·安全·php·web·反序列化
名字还没想好☜2 小时前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
淼澄研学3 小时前
Python实战:基于LangChain与Chroma构建企业级RAG知识库问答系统
开发语言·python·langchain