C 从套接字读取到std :: String
C++ Read From Socket into std::string
我正在用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;
}
因为 read()
*函数为参数带一个char数组指针。在这里返回字符串的最佳方法是什么?我知道我可以从理论上将数据读为char阵列,然后将其转换为字符串,但这对我来说似乎很浪费。有更好的方法吗?
*我实际上并不介意使用其他 read()
的东西,如果有一个更合适的替代方案
这是Pastebin上的所有代码,应该在一周内到期。如果我没有答案,那么我将重新调整它:http://pastebin.com/hktdzmst
[update]
我也尝试使用&output[0]
,但输出包含以下内容:
jello!
[insert a billion bell characters here]
"果冻!"是发送回插座的数据。
这里有一些功能可以帮助您完成所需的功能。它假设您只会从插座的另一端接收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;
}
或
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;
}
打印字符串时,请确保使用cout << output.c_str()
,因为字符串覆盖operator<<
并跳过无法打印的字符,直到达到大小为止。最终,您还可以在功能结束时调整大小,以便接收到的大小,并能够使用普通的cout
。
正如注释中指出的那样,首先发送大小也是一个好主意,避免字符串类可能不必要的内存分配。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL