Here are some functions that should help you accomplish what you want. It assumes you'll only receive ascii character from the other end of the socket.
std::string Communication::recv(int bytes) {
std::string output(bytes, 0);
if (read(this->sock, &output[0], bytes-1)<0) {
std::cerr << "Failed to read data from socket.\n";
}
return output;
}
or
std::string Communication::recv(int bytes) {
std::string output;
output.resize(bytes);
int bytes_received = read(this->sock, &output[0], bytes-1);
if (bytes_received<0) {
std::cerr << "Failed to read data from socket.\n";
return "";
}
output[bytes_received] = 0;
return output;
}
When printing the string, be sure to use cout << output.c_str()
since string overwrite operator<<
and skip unprintable character until it reaches size. Ultimately, you could also resize at the end of the function to the size received and be able to use normal cout
.
As pointed out in comments, sending the size first would also be a great idea to avoid possible unnecessary memory allocation by the string class.