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() */  
}
相关推荐
胡乱儿起个名21 分钟前
《高阶函数:把函数当玩具传来传去》
开发语言·c++·算法
七七知享22 分钟前
开启 Python 编程之旅:基础入门实战班全解析
开发语言·python·程序人生·程序员·零基础·实战
repetitiononeoneday23 分钟前
java基础课程-springmvc课程
java·开发语言
古月居GYH40 分钟前
嵌入式C语言高级编程:OOP封装、TDD测试与防御性编程实践
c语言·开发语言·tdd
ghost1431 小时前
Python自学第1天:变量,打印,类型转化
开发语言·python·学习
汤姆_5111 小时前
【c语言】深入理解指针1
c语言·开发语言
gospace1 小时前
Golang Event Bus 最佳实践:使用 NSQite 实现松耦合架构
开发语言·架构·golang·事件·总线·event·event bus
风中飘爻1 小时前
JavaScript:表单及正则表达式验证
开发语言·javascript·ecmascript
极客先躯2 小时前
高级java每日一道面试题-2025年4月07日-微服务篇[Nacos篇]-如何监控Nacos的运行状态?
java·开发语言·微服务
牛了爷爷2 小时前
php伪协议
android·开发语言·php