我正在编写一个使用c sockets的c++程序。我需要一个接收数据并返回字符串的函数。我知道以下代码不会起作用:
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;
}
由于
read()
函数需要一个字符数组指针作为参数。在这里,最好的返回字符串的方法是什么?我知道理论上可以将数据读入字符数组中,然后将其转换为字符串,但我觉得这样很浪费。有更好的方法吗?*如果有更合适的替代方案,我并不介意使用其他东西而不是
read()
。这是pastebin上的所有代码,它应该在一周内过期。如果那时候我还没有答案,我会重新发布它:http://pastebin.com/HkTDzmSt [更新]
我还尝试使用
&output[0]
,但输出包含以下内容:jello!
[insert a billion bell characters here]
"jello!"是发送回套接字的数据。
jello!\n
。 - 735Tesla