735*_*sla 7 c++ sockets stdstring
我正在编写一个使用c套接字的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;
}
Run Code Online (Sandbox Code Playgroud)
因为read()*函数采用char数组指针作为参数.在这里返回字符串的最佳方法是什么?我知道理论上我可以将数据读入char数组然后将其转换为字符串,但这对我来说似乎很浪费.有没有更好的办法?
*read()如果有更合适的选择,我实际上并不介意使用其他东西
以下是pastebin上应该在一周内到期的所有代码.如果我当时没有答案,我会重新发布:http://pastebin.com/HkTDzmSt
[UPDATE]
我也试过使用&output[0]但得到的输出包含以下内容:
jello!
[insert a billion bell characters here]
Run Code Online (Sandbox Code Playgroud)
"爽!" 是将数据发送回套接字.
这里有一些功能可以帮助你完成你想要的。它假设您只会从套接字的另一端接收 ascii 字符。
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;
}
Run Code Online (Sandbox Code Playgroud)
或者
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;
}
Run Code Online (Sandbox Code Playgroud)
打印字符串时,一定要使用cout << output.c_str()因为字符串覆盖operator<<并跳过不可打印的字符,直到它达到大小。最终,您还可以在函数结束时将大小调整为接收到的大小并能够使用正常的cout.
正如评论中指出的那样,首先发送大小也是一个好主意,以避免字符串类可能进行不必要的内存分配。
| 归档时间: |
|
| 查看次数: |
9484 次 |
| 最近记录: |