无法在 C++ 中通过套接字发送 ostringstream 变量

Cannot send ostringstream variable over socket in C++

有人可以向我解释为什么我使用 ostringstream 派生的 string 变量不能通过套接字发送吗?

std::ostringstream oss1;
std::ostringstream oss2;

int code = 52;

oss1 << "4" << "1" << "0" << "0" << "0" << "0" << 224 + code / 16 << code % 16;
oss2 << "4" << "0" << "0" << "0" << "0" << "0" << 224 + code / 16 << code % 16;

int msg_len3 = oss1.tellp;
int msg_len4 = oss2.tellp;

std::string var1 = oss1.str();
std::string var2 = oss2.str();

comm_send1 = send(sock, var1, msg_len3, 0);
comm_send2 = send(sock, var2, msg_len4, 0);

使用此代码我收到以下错误:

no suitable conversion function from std::string to const char* exists

因为 send() 函数需要一个 const char * 参数,而不是 std::string,这是 .str() 给你的。

试试这个:

comm_send1 = send(sock, var1.c_str(), msg_len3, 0);

std::string.c_str() 成员函数为您提供所需的类型:C 风格的字符串。