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() */  
}
相关推荐
未来可期LJ30 分钟前
【C++ 设计模式】单例模式的两种懒汉式和饿汉式
c++·单例模式·设计模式
Trouvaille ~1 小时前
【C++篇】C++类与对象深度解析(六):全面剖析拷贝省略、RVO、NRVO优化策略
c++·c++20·编译原理·编译器·类和对象·rvo·nrvo
little redcap1 小时前
第十九次CCF计算机软件能力认证-乔乔和牛牛逛超市
数据结构·c++·算法
AI原吾2 小时前
掌握Python-uinput:打造你的输入设备控制大师
开发语言·python·apython-uinput
机器视觉知识推荐、就业指导2 小时前
Qt/C++事件过滤器与控件响应重写的使用、场景的不同
开发语言·数据库·c++·qt
毕设木哥2 小时前
25届计算机专业毕设选题推荐-基于python的二手电子设备交易平台【源码+文档+讲解】
开发语言·python·计算机·django·毕业设计·课程设计·毕设
珞瑜·2 小时前
Matlab R2024B软件安装教程
开发语言·matlab
weixin_455446172 小时前
Python学习的主要知识框架
开发语言·python·学习
孤寂大仙v2 小时前
【C++】STL----list常见用法
开发语言·c++·list
她似晚风般温柔7893 小时前
Uniapp + Vue3 + Vite +Uview + Pinia 分商家实现购物车功能(最新附源码保姆级)
开发语言·javascript·uni-app