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() */  
}
相关推荐
敲上瘾13 小时前
Qt核心机制:信号与槽详解
开发语言·c++·qt·ui·qt6.3
联犀14 小时前
ai时代复杂项目的golang项目如何更好的与ai共舞:monorepo+gozero
开发语言·人工智能·golang
牢姐与蒯14 小时前
cpp算法之哈希
c++·算法·哈希算法
lcj251116 小时前
[C++] C++11
开发语言·c++·笔记
Evand J17 小时前
【MATLAB例程】基于IMM-CKF的AOA+测距融合的二维移动目标跟踪定位
开发语言·matlab·目标跟踪
JianZhen✓18 小时前
IM 聊天列表为什么总“消息乱跳“:有序插入、时间轴派生、本地截断、已读回执
开发语言·前端·php
FungLeo19 小时前
FengCMS · PHP+MySQL 升级实录· 代码审计怎么闭环:REVIEW到 CLOSURE 四件套,12 个域90 篇修复文档跟到底
开发语言·mysql·php·代码审计·fengcms
七夜zippoe19 小时前
多轮对话管理:Session/记忆在 Java 后端怎么存(存储设计实战)
java·开发语言·ai·session·记忆
小小bugbug19 小时前
带工作窃取的线程池
c++·线程池
屿华AI19 小时前
AUTOSAR 实战-诊断工具 | 基于 Python 与 USB-CANFD 的 UDS 诊断测试工具设计与实现
开发语言·python·测试工具