c++ char  convert to string

mendes paulo
mendes paulo used Ask the Experts™
on
HOW TO CONVERT * char to string (linha):

const unsigned char
*menino1 = (const unsigned char *)0;


menino1 = p - 17;

string linha = menino[1]+menino[2]+menino[3]+menino[4]+menino[5];
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Just use the std::string constructor and pass it the menino1.

http://www.cplusplus.com/reference/string/string/string/ See the variant (4) if your bytes are ended with zero or (5) passing the length -- this may be more suitable for your case... like
string linha(menino1, 5);

Open in new window

Top Expert 2016
Commented:
const unsigned char
*menino1 = (const unsigned char *)0;

char strings in c++ normally are signed char. unsigned char is called byte and normally contains a binary 8-bit unsigned integer.

so your code normally would be turned to

char * menoino1 = NULL;  // or 0

Open in new window


what means that you have defined a null pointer to char.

that allows you to point to a single char or to point to the first char of a char array:

char str[5] = { 'a', 'b', 'c', 'd', '\0' };
menoino1 = & str[0];   
// or 
menoino1 = str;   // what is equivalent

Open in new window


instead of

char str[5] = { 'a', 'b', 'c', 'd', '\0' };

Open in new window


you can omit the '\0' which is default. or you can do:

char str[5] = "abcd";

Open in new window


what also is equivalent.

char pointers and char arrays are mostly equivalent. the only difference is that sizeof(menoino1) is pointer size (==4 on most systems) while sizeof(str) is 5.

menino1 = p - 17;
string linha = menino[1]+menino[2]+menino[3]+menino[4]+menino[5];

what is p?

p-17 is dangerous code beside you are sure that p is a valid char * and points to 17th (or higher) element in another char array.

a string is a class object which allows to handle char arrays without to bother with pointers.

for the above statement you would do

string linha = string(menino, 5);

Open in new window


that means you were using a constructor isf std::string which takes a poiter to char and the number of chars you want to take from pointer.

note, the statement will crash if menino is a NULL pointer.

string linha(menino1, 5);

this suggestion from pepr will some compilers deny if it is used as standalone statement and not at the right side of an assignment since it is might be considered as ambiguous.

Sara
Detailed explanation provided. The answer is good source for learning.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial