C++ 将const char*转换为std::string时,数据丢失
在这个例子中 *只需将const char*值作为输入(即:test one) *将常量字符*转换为std::字符串 *传递std::string的值以压缩字符串 *字符串压缩,可以看到压缩字符串的值 *压缩字符串::x�+智商��高# *现在将压缩数据的std::字符串转换为const char* *当我做这一步时,只得到75%的数据,几乎没有数据丢失 例:x�+智商��K *我需要做什么才能得到全部数据 *有人能在这方面帮助我吗C++ 将const char*转换为std::string时,数据丢失,c++,string,c++11,zlib,C++,String,C++11,Zlib,在这个例子中 *只需将const char*值作为输入(即:test one) *将常量字符*转换为std::字符串 *传递std::string的值以压缩字符串 *字符串压缩,可以看到压缩字符串的值 *压缩字符串::x�+智商��高# *现在将压缩数据的std::字符串转换为const char* *当我做这一步时,只得到75%的数据,几乎没有数据丢失 例:x�+智商��K *我需要做什么才能得到全部数据 *有人能在这方面帮助我吗 int main ( int argc,char
int main ( int argc,char *argv[] )
{
const char *str = "test one";
int length = 0;
std::string compressionString(str);//converting char * to std::string
cout << "compressionString::" << compressionString<< endl;
while(*(str+length))
length++; //length of char *
cout << "Length of entered string:: " <<length << endl;
std::string compStr = compress_string(compressionString);//Compress the string using compress_string()
cout << "compressed String::"<<compStr << endl;
const char* m_pcompCharptr = compStr.c_str();
cout << "Compressed string char* length::"<< sizeof(m_pcompCharptr) <<endl;
cout << "Compressed value which is present in char * is :: " <<m_pcompCharptr << endl;
cout << "Compressed String length:: " << compStr.length() << endl;
int iCompLen = compStr.length();
cout << "iCompLen::" << iCompLen << endl;
std::string decompressionString(m_pcompCharptr);//converting const char* to std::string
std::string decompStr = decompress_string(decompressionString);
cout << "decompStr::" << decompStr << endl;
return 0;
}
intmain(intargc,char*argv[])
{
const char*str=“测试一”;
整数长度=0;
std::string compressionString(str);//将char*转换为std::string
当你这样做的时候
const char* m_pcompCharptr = compStr.c_str();
…您在compStr
中的第一个字符处获得一个const char*
,它本身没有长度/大小的概念或记录。如果您随后使用上面的const char*
构造字符串
std::string decompressionString(m_pcompCharptr);
std::string
构造函数对const char*
的重载依赖于ASCIIZ编码来检测传入字符串的长度:这意味着它认为文本在第一个NUL字符处结束
这不是一个错误…在处理二进制字符串时,您确实需要保留.size()
中的const char*
和size\t
值(您在length
中有效地捕获了该值),以便像这样重建字符串
:
std::string decompressionString(m_pcompCharptr, length);
我不会将压缩字符串放入字符串中。特别是因为它可能不再被视为字符串。我猜压缩字符串中有一个空字节。如果使用std::string decompressionString(m_pcompCharptr,compStr.size())是否有效
在第四行到最后一行?这个问题我几乎无法理解。请使用完整的句子并改进格式,以便清楚地标记代码片段等。可能您有一个嵌入的NUL字节(0x00).std::string
可以包含NUL字节,但普通的const char*
不能包含NUL字节,因为它们使用该值作为终止符。您应该真正使用std::vector
而不是二进制数据中的std::string
。@πάνταῥεῖ hmmm strlen(str)+1包括终止符。while是一种计算长度的奇怪方法,但它会起作用。无论如何,我都会替换它。