istringstream operator>> return value

时间:2017-06-19 14:06:56

标签: c++ tcp istream istringstream

Unfortunately this was not helpful...

I have a software which throws an exception as implemented, but I need to know how to avoid it. Here is the specific part:

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

And this is the whole method.

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;

The method parses the data content of an tcp message answer. Each message gets acknowledged with an ">" character.

The issue is now, that sometimes (mostly when a lots of messages are in the loop) the content of iss is:

"> 250 Alright"

The correct format would be

"250 Alright"

  • Why does (iss >> c) return false when the first content of iss is a ">"?
  • Is it possible that the sender returned a second ">" in his answer?

Thanks in advance

1 个答案:

答案 0 :(得分:2)

  

当iss的第一个内容是">"?

时,为什么(iss>> c)会返回false

当读入的字符是">"时,iss >> c会返回false。因为它期望一个整数并想要将值赋给变量c,当它无法找到这样的整数时,istream会进入错误状态。

  

发件人是否可能返回第二个">"在他的回答中?

您可能只是在输入流中留下了您无法读入的剩余值(因为上述原因),您在"状态"

中看到