char *, char[], and string in C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// char * and char[] to string
char * p = "Hello, world!\n";
char c[] = "Hello, world!\n";
std::string str1(p), str2(c);
cout << str1 << str2 << endl;

// string to char * and char[]
char cc[10];
char *pp;
strcpy(cc, str1.c_str());
strcpy(pp, str1.c_str());
cout << cc << pp << endl;

// char[] to char *
char ccc[] = "Hello, world!\n";
char *ppp = ccc;
cout << ppp << endl;

// char * to char[]
char *pppp = "Hello, world!\n";
char cccc[10];
strcpy(cccc, pppp);
cout << cccc << endl;
  • To use string, you should include .
  • To user strcpy, you should include or <string.h>.