简体   繁体   English

cout字符串和c_str在c ++中给出不同的值

[英]cout string and c_str gives different values in c++

In my code, I have a string variable named ChannelPacket. 在我的代码中,我有一个名为ChannelPacket的字符串变量。 when I print Channelpacket in gdb, it gives following string : "\\020\\000B\\001\\237\\246&\\b\\000\\016\\000\\002\\064\\001\\000\\000\\005\\000\\021\\002\\000\\000\\006\\000\\f\\001\\001\\000\\000sZK" 当我在gdb中打印Channelpacket时,它给出以下字符串:“ \\ 020 \\ 000B \\ 001 \\ 237 \\ 246&\\ b \\ 000 \\ 016 \\ 000 \\ 002 \\ 064 \\ 001 \\ 000 \\ 000 \\ 005 \\ 000 \\ 021 \\ 002 \\ 000 \\ 000 \\ 006 \\ 000 \\ f \\ 001 \\ 001 \\ 000 \\ 000sZK“

But if i print Channelpacket.c_str(), it gives just "\\020 output. Please help me. 但是,如果我打印Channelpacket.c_str(),它只会输出“ \\ 020”。请帮助我。

c_str() returns a pointer to char that's understood to be terminated by a NUL character ( '\\0' ). c_str()返回指向char的指针,该指针被理解为以NUL字符( '\\0' )终止。

Since your string contains an embedded '\\0' , it's seen as the end of the string when viewed as a pointer to char. 由于您的字符串包含嵌入的'\\0' ,因此当被视为指向char的指针时,它被视为字符串的结尾。

When viewed as an actual std::string , the string's length is known, so the whole thing is written out, regardless of the embedded NUL characters. 当以实际std::string查看时,字符串的长度是已知的,因此,无论嵌入的NUL字符如何,整个内容都会写出。

The second byte is a zero, which means the end of the string. 第二个字节为零,表示字符串的结尾。 If you want to output the raw bytes, rather than treating them as a null-terminated string, you can't use cout << Channelpacket.c_str() - use cout << Channelpacket instead. 如果要输出原始字节,而不是将它们视为以null终止的字符串,则不能使用cout << Channelpacket.c_str() -而是使用cout << Channelpacket

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

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