c_str()的奇怪行为

时间:2018-10-28 07:27:12

标签: c++

使用posix套接字时怎么了

 write(new_socket, method.c_str(), sizeof(method.c_str()));

有效但是

write(new_socket, method.c_str(), method.length());

write(new_socket, method.c_str(), method.size());

不起作用?

方法是4个字符串。

sizeof(method.c_str())返回8。

method.length()返回4。

method.size()返回4。

strlen(method_c_str())返回4。

1 个答案:

答案 0 :(得分:-1)

函数的第三个参数采用要发送的字节数。 但是size()和length()返回字符数。 我认为您使用了一串UTF-16字符,每个字符需要2个字节。 在这种情况下,将字符数(按大小返回)乘以2可能是一种解决方案。

相关问题