I am writing a program in c++ that uses c sockets. I need a function to receive data that I would like to return a string. I know this will not work:
std::string Communication::recv(int bytes) {
std::string output;
if (read(this->sock, output, bytes)<0) {
std::cerr << "Failed to read data from socket.\n";
}
return output;
}
Because the read()
* function takes a char array pointer for an argument. What is the best way to return a string here? I know I could theoretically read the data into a char array then convert that to a string but that seems wasteful to me. Is there a better way?
*I don't actually mind using something other that read()
if there is a more fitting alternative
Here is all of the code on pastebin which should expire in a week. If I don't have an answer by then I will re-post it: http://pastebin.com/HkTDzmSt
[UPDATE]
I also tried using &output[0]
but got the output contained the following:
jello!
[insert a billion bell characters here]
"jello!" was the data sent back to the socket.