string convert
Prerequisites:
to_string
將整數轉成string
1
2
string str = to_string(2022 + 23);
cout << "str = " << str << endl;
str = 2045
string to char指標
1
2
3
4
5
6
7
8
9
10
11
// char指標陣列
#include <iostream>
using namespace std;
int main() {
char* arr[10];
arr[0] = (char*)"test";
arr[1] = (char*)"/123";
cout << "arr[0] = " << arr[0] << endl;
cout << "arr[1] = " << arr[1] << endl;
return 0;
}
arr[0] = test
arr[1] = /123
const string to char指標
c_str()是取得string物件位址
1
2
3
4
const string title = "被討厭的勇氣";
char* s = new char[100];
strcpy(s, title.c_str());
cout << "s = " << s << endl;
s = 被討厭的勇氣
char* to string
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <cstring>
using namespace std;
int main() {
// 有const char*
const char* c_s1 = "Hello world!";
// 沒const char*
char* c_s2 = " Hi! Mary!";
// 把其中一個char*變成string,就可以套用operator+= (const char* s)
string s1 = string(c_s1) + c_s2;
cout << "s1 = " << s1 << endl;
return 0;
}
s1 = Hello world! Hi! Mary!