Translate the code from Python to C++ -
now when understand how code works, translate c++.
the original python code:
def recv_all_until(s, crlf): data = "" while data[-len(crlf):] != crlf: data += s.recv(1) return data
here's tried:
std::string recv_all_until(int socket, std::string crlf) { std::string data = ""; char buffer[1]; memset(buffer, 0, 1); while(data.substr(data.length()-2, data.length()) != crlf) { if ((recv(socket, buffer, 1, 0)) == 0) { if (errno != 0) { close(socket); perror("recv"); exit(1); } } data = data + std::string(buffer); memset(buffer, 0, 1); } return data; }
but shows:
terminate called after throwing instance of 'std::out_of_range' what(): basic_string::substr
i understand problem inside while
loop since @ first data string empty. how improve make work same works in python? thank you.
if first change python code bit:
def recv_all_until(s, crlf): data = "" while not data.endswith(crlf): data += s.recv(1) return data
what need in c++ becomes clearer:
bool ends_with(const std::string& str, const std::string& suffix) { return str.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), str.rbegin()); } std::string recv_all_until(int socket, const std::string& crlf) { std::string data = ""; char buffer[1]; memset(buffer, 0, 1); while (!ends_with(data, crlf)) { if ((recv(socket, buffer, 1, 0)) == 0) { if (errno != 0) { close(socket); perror("recv"); exit(1); } } data = data + std::string(buffer); memset(buffer, 0, 1); } return data; }
Comments
Post a Comment