1

在我的程序中,我要求用户通过 getline 输入,然后在一个单独的类中,将字符串拆分为三个不同的字符串,然后我将通过预先确定的值列表进行检查。

现在的工作方式,如果有人输入了无效的命令,我会显示“INVALID”

我遇到的问题是一个只包含空格或一个换行符的字符串。

这是我正在尝试做的事情:

std::string command; // command user enters
getline(std::cin, command); // user input here

std::string tempCheck; // if we have a value in here other than empty, invalid
// use istringstream to grab the words, max of 3
std::istringstream parse{fullCommand}; // parse command into words

if(fullCommand.empty()){ // nothing has been input
    std::cout << "INVALID" << std::endl;
    return;
}

parse >> command; // stores first word (the command)
parse >> actionOne; // stores second word as parameter
parse >> actionTwo; // stores third word as parameter
parse >> tempCheck;

if(!tempCheck.empty()) {
    std::cout << "INVALID" << std::endl;
    return;
}

变量 tempCheck 基本上意味着如果它超过三个字(我想要的命令限制),那么它就是无效的。我还认为有一个空字符串会起作用,但是当没有输入任何内容时,它只会以无限循环结束,但我只是按 Enter 键。

这是我希望我的输入做的事情(粗体是输出):

CREATE username password
**CREATED**
      LOGIN          username password
**SUCCEEDED**
ASDF lol lol
**INVALID**

**INVALID**
REMOVE username
**REMOVED**

**INVALID**
QUIT
**GOODBYE**

这是正在发生的事情:

CREATE username password
**CREATED**
 // newline entered here

它进入了一个看似无限的循环。我仍然可以输入东西,但是,它们实际上并没有影响任何东西。例如,键入 QUIT 什么都不做。但是,如果我重新启动程序并仅键入“QUIT”而不尝试仅使用换行符或仅使用空格,则会得到预期的输出:

QUIT
**GOODBYE**

那么,我如何告诉 getline 或我的 istringstream,如果用户只是输入一堆空格然后按 Enter,或者如果用户只是按 Enter,则显示无效并返回?无论如何只用 getline 或 istringstream 就可以做到这一点吗?

4

1 回答 1

0

亚历克斯,以下代码可能会有所帮助:

std::string strip(std::string const& s, std::string const& white=" \t\n")
{
    std::string::size_type const first = s.find_first_not_of(white);
    return (first == std::string::npos)
        ? std::string()
        : s.substr(first, s.find_last_not_of(white)-first+1);
}

您可以在创建之前应用它istringstream

std::istringstream parse{strip(fullCommand)};

上面的代码是从旧的众所周知的技术中借用和稍微修改的。

于 2014-12-01T00:27:47.020 回答