【问题标题】:Detect a newline character with getline or istringstream使用 getline 或 istringstream 检测换行符
【发布时间】:2015-01-25 14:29:27
【问题描述】:

在我的程序中,我通过 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 基本上意味着如果它超过三个单词(我想要的命令限制),那么它就是无效的。我还认为有一个空字符串会起作用,但是当没有输入任何内容时,它只会以无限循环结束,但我只是按了回车键。

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

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 来做到这一点?

【问题讨论】:

  • getlineistringstream 并不像你想象的那样相互排斥。
  • 如果您可以发布MCVE、示例输入和预期输出,将会很有帮助。
  • @chris 那么我该如何让它们正确地协同工作呢?我只是认为 getline 一直到它遇到换行符,而 istringstream 存储由空格或换行符分隔的字符
  • @RSahu 我添加了示例输入和预期输出,以及当我这样做时会发生什么。
  • @Alex 您可以在处理之前检查字符串是否全是空格。

标签: c++ string parsing getline istringstream


【解决方案1】:

Alex,下面的代码可能会有所帮助:

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)};

以上代码是从the old well-known technique借用并稍作修改的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多