模拟命令行

设计初衷

​ 命令行是通过输入各种命令来完成你想要做的事情。而用户输入命令的格式千奇百怪,所以终端需要先对命令进行解析(我猜的)才能执行进行相关的命令。

​ 让我想写这个程序的初衷是因为感觉这个东西非常的炫酷,他将一堆杂乱无章的数据整理后得到了整齐划一的数据,这种从混沌到秩序的变化非常的美丽、迷人。


程序的功能

​ 其实实现的功能非常简单:让用户输入命令,以空格作为分割,以分号作为结束,将解析后的命令用vector<string>返回。


设计思路

使用C++中的getline命令不断获取内容,之后从前往后遍历字符串,找到空格就push_back,找到分号就停止遍历并返回字符串。


代码

#include <string>
#include <iostream>
#include <vector>

std::vector<std::string> getCommand() {
    std::string read_s, t;
    std::getline(std::cin, read_s);
    std::vector<std::string>res;

    bool flag = false;

    while (!flag) { /* 没有找到分号 */
        for (std::string::iterator it = read_s.begin(); it != read_s.end(); it++) {
            if ((*it) == ' ' || (*it) == ';') { /* 找到空格或者分号 */
                if(t.size() != 0) {
                    res.push_back(t);
                    t.clear();
                }

                if ((*it) == ';') { /* 找到分号 */
                    flag = true;
                    break;
                }
            } else {
                t = t + (*it);
            }
        }

        if (t.size() != 0) {
            res.push_back(t);
            t.clear();
        }
        if (!flag) {
            std::getline(std::cin, read_s);
        }
    }
    return res;
}

int main() {
    while (true) {
        std::vector<std::string>res = getCommand();
        if (res.size() == 1 && res[0] == "exit") {
            break;
        }
        for (auto it : res) {
            std::cout << it << std::endl;
        }
    }

    return 0;
}

posted @ 2021-01-27 11:53  牟翔宇  阅读(85)  评论(0编辑  收藏  举报