简体   繁体   中英

Strangeness with special characters in C-strings and unprintable ASCII

I need to copy a c++ string into a char array and then decode it. The char array does not need to be null terminated. Due to the encoded nature, many of the characters are unusual, and some are non-printable, and this is causing issues.

This is what the C++ string prints as: std::cout << myString; Output:

mw\22ypwr\`himg 0few1nvnl

This is converted into a char [] by doing the following:

char * m = new char[myString.size() + 1];
strcpy(m, myString.c_str());

m* has a length of 24, and is not correct. It fails to properly decode. The following char [] does decode properly:

char m2 [] = "mw\22ypwr`himg 0few1nvnl";

Note that this is created by copying the output of the string. However, the length of this c-string is just 22, not 24. Furthermore, printing it has the following result:

std::cout << m;

Output:

mwypwr`himg 0few1nvnl

Note that the \22 is gone. However, it's not as simple as removing that from the string before converting it to a char[] . Iterating through the ASCII values shows that there is a character with the decimal opcode of 18 , where the \22 used to be. This character does not print.

ASCII values as decimal:

109 119 18 121 112 119 114 96 104 105 109 103 32 48 102 101 119 49 110 118 110 108 

Why does the \22 get converted into ASCII character 18? How can I construct the proper, de-codable C-string from the C++ string that has the literal \22 ? I need to be able to do this for a large list of potentially unknown encoded strings, so I would prefer not to manually replace \22 with ASCII 18 without at least knowing why this happens.

The character string contains escape sequences that denote octal characters .

"mw\22ypwr\...other characters..."

The \22 is octal for decimal 18, thus the output you're seeing when you display the numeric version of each character.

if the c++ string s not zero terminated then this wont work

strcpy(m, myString.c_str());

strcpy copies till zero encountered, use memcpy instead

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