简体   繁体   中英

Cannot send ostringstream variable over socket in C++

Could someone please, explain to me why a string variable I have derived using ostringstream cannot be sent over a socket?

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);

With this code I am getting an error of:

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

Because the send() function requires a const char * argument, not a std::string , which is what .str() gives you.

Try this instead:

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

The .c_str() member function of std::string gives you the type you need: a C-style string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM