Jak przekonwertować tablicę znaków na łańcuch znaków?

Konwersja C++ string do tablicy znaków jest dość prosta, używając c_str funkcji string, a następnie wykonując strcpy. Jak jednak zrobić coś przeciwnego?

Mam tablicę znaków typu: char arr[ ] = "This is a test"; do konwersji z powrotem na: string str = "This is a test.

Author: Tshepang, 2012-01-22

5 answers

Klasa string ma konstruktor, który przyjmuje zakończony znakiem null łańcuch C:

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

// or
str = arr;
 310
Author: Mysticial,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-21 07:49:49

Inne rozwiązanie może wyglądać tak,

char arr[] = "mom";
std::cout << "hi " << std::string(arr);

, który pozwala uniknąć użycia dodatkowej zmiennej.

 47
Author: stackPusher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-27 20:10:36

Jest mały problem pominięty w najczęściej głosowanych odpowiedziach. Mianowicie, tablica znaków może zawierać 0. Jeśli użyjemy konstruktora z pojedynczym parametrem, jak wskazano powyżej, stracimy pewne dane. Możliwe rozwiązanie to:

cout << string("123\0 123") << endl;
cout << string("123\0 123", 8) << endl;

Wyjście To:

123
123 123

 15
Author: Yola,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-16 14:02:26
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;

int main ()
{
  char *tmp = (char *)malloc(128);
  int n=sprintf(tmp, "Hello from Chile.");

  string tmp_str = tmp;


  cout << *tmp << " : is a char array beginning with " <<n <<" chars long\n" << endl;
  cout << tmp_str << " : is a string with " <<n <<" chars long\n" << endl;

 free(tmp); 
 return 0;
}

OUT:

H : is a char array beginning with 17 chars long

Hello from Chile. :is a string with 17 chars long
 8
Author: Cristian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-26 16:38:09

W C++ 11 możesz użyć std::to_string("bla bla bla");

 -9
Author: joilnen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-17 10:54:43