两个单词命令命令 C++

two word commands commands C++

您好,打扰您了,我正在尝试编写两个单词的命令 用户将键入 "go north" 我希望我的程序获取这两个词并将它们分别放入变量中,我编写的程序正在执行但是当我键入一个单词命令时他的编译器正在等待第二个命令我怎么能写这个简单的方法来说明如果没有第二个命令 grab input 1 without waiting second entry 谢谢

    cin >> input1 >> input2;
    if(!(input2==""))
    {
        if (input1 == "take" or input1 == "grab" or input1 == "go")
            input = input2;
        else
            input = input1;
    }
    else
        input = input1;
    input = format(input);

两个选项:您可以使用std::getline 读取整行然后解析该行。以最少的更改修复代码的方法是先读一个词,然后再读另一个词,而不是同时读两个词:

cin >> input1;
if (input1 == "take" or input1 == "grab" or input1 == "go") {
    cin >> input2;
    input = input2;
} else {
    input = input1;
}

如果您不想输入超过一个词,则需要使用 std::getline

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

并解析您可以使用的行 boost::split

std::vector<std::string> words;
boost::split(words, command, boost::is_any_of(" "));

所以你的代码应该像这样

std::string command;
std::getline(cin, command);
std::vector<std::string> words;
boost::split(words, command, boost::is_any_of(" "));

现在执行命令检查