【问题标题】:istringstream operator>> return valueistringstream 运算符>>返回值
【发布时间】:2017-06-19 14:06:56
【问题描述】:

很遗憾,this 没有帮助...

我有一个软件在实现时会引发异常,但我需要知道如何避免它。下面是具体部分:

if (!(iss >> c)) {
    throw std::runtime_error(
        "No return code: status line doesn't begin with return code");
}

这就是整个方法。

void parseReply(std::ostream& os, std::istream& is, std::string &strReturn) {

std::string s;
int     c;

while (std::getline(is, s)) {
    strReturn += s;
    strReturn += '\n';

    std::istringstream iss(s);
    if (!(iss >> c)) {
        throw std::runtime_error(
            "No return code: status line doesn't begin with return code");
    }

    if (CODE_OK == c
        || CODE_ERROR == c
        || CODE_BUSSY == c
        || CODE_UNKNOWN_CMD == c
        ) {
        break;
    }
}

if (CODE_OK != c
    &&  CODE_UNKNOWN_CMD != c
    &&  CODE_BUSSY != c
    )  {
    throw std::runtime_error("error: " + s);
}

while (is >> s) {       
    flyelite::util::chop(s);        
    strReturn += s;
    if (">" == s) {         
        return;
    }
}

return;

该方法解析 tcp 消息应答的数据内容。每条消息都使用“>”字符进行确认。

现在的问题是,有时(主要是当有很多消息在循环中时)iss 的内容是:

">250 好的"

正确的格式是

“250 好”

  • iss的第一个内容是“>”时,为什么(iss >> c)返回false
  • 发件人是否有可能在他的回答中返回了第二个“>”?

提前致谢

【问题讨论】:

    标签: c++ tcp istream istringstream


    【解决方案1】:

    当iss的第一个内容是“>”时,为什么(iss >> c)返回false?

    iss >> c 在读入的字符是“>”时返回 false,因为它需要一个整数,并希望将值分配给变量 c,但无法找到这样的整数,然后istream 进入错误状态。

    发件人是否有可能在他的回答中返回了第二个“>”?

    您在“状态”中看到的可能只是输入流中您无法读取的剩余值(由于上述原因)

    【讨论】:

    • 感谢@Curious,所以操作员>>对“目标”类型很敏感......很好
    猜你喜欢
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2013-07-31
    • 2019-12-29
    • 2019-04-14
    • 1970-01-01
    相关资源
    最近更新 更多