Home c++ Converting char to string

Converting char [] to string

Author

Date

Category

There is an array char [] . We need to convert it to string .
How can this be done most simply?


Answer 1, authority 100%

Read this article: “Strings as null terminated char arrays. “.

Here’s a quick excerpt:

One way to organize your work with strings is to use
one-dimensional arrays of type char . Then the character string is one-dimensional
an array of type char , null terminated.

A null byte is a byte, each bit of which is equal to zero, while for
zero byte character constant \ 0 is defined (terminator
strings, or null terminator). Zero byte functions that work with
lines, determine where the line ends. If they are reading a line,
then they perceive it only up to the first null terminator; if they
create a string, write a null terminator at the end.

It will also be useful to read the answer to this question: How to convert a char array to a string?

Here’s the solution:

char arr [] = "Simple check";
string str = string (arr);
cout & lt; & lt; str;
// "Simple check"

Here’s an example at Ideone


Answer 2, authority 100%

If the array contains a C string ending with '\ 0' , then simply by assigning

char s [] = "test";
std :: string str = s;
// or explicitly as a constructor parameter
std :: string str2 (s);

If '\ 0' does not end, then you must explicitly specify the size

char s [] = {'t', 'e', ​​'s', 't'};
std :: string str (s, sizeof (s));

Answer 3

Well, by simple assignment …

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions