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

  • The easiest way is to familiarize yourself with the list of std :: string constructors. Or you do not read the documentation on what you use? - αλεχολυτ

3 answers 3

Read this article: " Strings as null-terminated arrays of char. ".

Here is a brief excerpt:

One way to organize work with strings is to use one-dimensional arrays of type char . Then the character string is a one-dimensional array of type char ending in a zero byte.

The zero byte is a byte, each bit of which is equal to zero, and the symbolic constant \0 (a terminator, or a null terminator) is defined for the zero byte. By the zero byte, functions working with strings determine the place where the string ends. If they read a string, they only perceive it before the first null terminator; if they create a string, they write a null-terminator at its end.

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

Here is the solution:

 char arr[ ] = "Простая проверка"; string str = string(arr); cout << str; // "Простая проверка" 

Here is an example on Ideone

    If the array contains a string ending in '\0' , then just assignment

     char s[] = "test"; std::string str = s; // или явно как параметр конструктора std::string str2(s); 

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

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

      Well, simple assignment is ...

      • 2
        Give an example, I think this is a good question, I have repeatedly come across it - Vasily Barbashev
      • It is not the answer to the question. To leave your comments or ask the author to clarify, leave a comment to the appropriate post. - From the queue of checks - VAndrJ
      • @VAndrJ, so why not? - Qwertiy