C++多个单词命令

multiple word commands C++

本文关键字:命令 单词 C++      更新时间:2023-10-16

我对C++有点陌生,很抱歉,如果这个问题很明显,但我遇到了一些障碍。我想做的是有一个命令提示符来执行某些事情。您输入简单的命令,例如timer down 10,它将启动计时器倒计时,我已经做得很好。我检测每个单词的方式是这样的:

string cmd1;
string cmd2;
int cmd3;
cin >> cmd1 >> cmd2 >> cmd3;

这工作正常,除了我想使用单个单词的命令,而有了这个系统,我真的做不到。例如,如果我想help作为命令,当我只想键入 1 个字符串时,它会让我键入 2 个字符串和一个 int。但是我希望有特定的命令,可以是完整的 2 个字符串和一个 int 或只有 1 个字符串。

使用 getline 将整个命令存储在单个字符串中。

String command;
std::getline (std::cin,command);

现在,您可以使用以下代码将命令拆分为标记字。

int counter =0;
string words[10];
for (int i = 0; i<command.length(); i++){
    if (command[i] == ' ')
        counter++;
    else
        words[counter] += command[i];
}

您需要使用 getline 读取命令,然后将其拆分为标记。 检查getline函数,并在谷歌上为标记 c++ 提供分割线

您可以

逐行读取输入,然后将每行拆分为包含每个命令后跟其参数的std::vector

void command_help()
{
    // display help
}
void command_timer(std::string const& ctrl, std::string const& time)
{
    int t = std::stoi(time);
    // ... etc ...
}
int main()
{
    // read the input one line at a time
    for(std::string line; std::getline(std::cin, line);)
    {
        // convert each input line into a stream
        std::istringstream iss(line);
        std::vector<std::string> args;
        // read each item from the stream into a vector
        for(std::string arg; iss >> arg;)
            args.push_back(arg);
        // ignore blank lines
        if(args.empty())
            continue;
        // Now your vector contains
        args[0]; // the command
        args[1]; // first argument
        args[2]; // second argument
        // ...
        args[n]; // nth argument
        // so you could use it like this
        if(args[0] == "help")
            command_help(); // no arguments
        else if(args[0] == "timer")
        {
            if(args.size() != 3)
                throw std::runtime_error("wrong number of arguments to command: " + args[0]);
            command_timer(args[1], args[2]); // takes two arguments
        }
    }
}