简体   繁体   English

string和string.c_str()的值不同

[英]different values of string and string.c_str()

i'm trying to send a file through the network using c++. 我正在尝试使用C ++通过网络发送文件。 first of all, i read my file and buffer it into a string and then i convert my string to c_str() and send it by my socket class 首先,我读取文件并将其缓冲为字符串,然后将字符串转换为c_str()并由我的套接字类发送

i have a problem with when i send my data, it doesn't output correctly. 我在发送数据时遇到问题,无法正确输出。 i wrote the following code to check that and i realize that the value of my string and string.c_str() is different from each other 我写了以下代码进行检查,并意识到我的string和string.c_str()的值彼此不同

ifstream source(path.c_str(), ios::binary);   
ostringstream out;
out << source.rdbuf();

string msg = out.str();

source.close();

cout << "msg: " << msg << endl;
printf("sent - %s\n", message.c_str());

the result of this two line is different. 这两行的结果是不同的。 "cout" prints my file's characters but printf just print 3 characters “ cout”打印我文件的字符,但是printf只打印3个字符

why this happen? 为什么会这样?

thanks a lot your help 非常感谢您的帮助

看来该字符串在第三个字符之后包含嵌入的零“ \\ 0”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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