Search code examples
c++tcpistreamistringstream

istringstream operator>> return value


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


Solution

  • Why does (iss >> c) return false when the first content of iss is a ">"?

    The iss >> c returns a false when the character that was read in is a ">" because it is expecting an integer and wants to assign the value to the variable c, when it is unable to find such an integer, then the istream goes into an error state.

    Is it possible that the sender returned a second ">" in his answer?

    It is likely just the left over value from the input stream that you were not able to read in (because of the above reason) that you see in your "state"