In C++, char, char*, int, string conversion function and string conversion function

1. Char to int and int to char
1.1, char to int:

char a = '1';
int b = a - '0'; // b = 1;

1.2, int to char:

int a = 1;
char b = a + '0'; // b = '1';

2. Char star, char to string and strng to char star, char
2.1, char star, char to string:

char* ptr = "abcd";
string s(ptr); // s = "abcd";

char c = 'a';
string s2;
s2 += c; // s2 = "c";

2.2. Convert strng to char star, char:

string s = "abc";
char* ptr = const_cast<char*>(s.c_str()); // ptr = "abc";

string s = "a";
char c = s[0]; // c = 'a';

3. Int to string and string to int
3.1, int to string:

int a = 23;
string s = to_string(a); // s = "23";

3.2, string to int:

string s = "123";
int a = atoi(s.c_str()); // a = 123;

4. The
function prototype of string to different hexadecimal number (strtol) :

long int strtol (const char* str, char** endptr, int base);

The meaning of each parameter:
strthe character
enptrto be converted is a pointer to the position of the first non-convertible character: if endptr is not NULL, the character pointer encountered that does not meet the conditions and terminates will be returned by endptr; if endptr is NULL, the pointer is not returned.
baseThe base of, which means the number converted into a decimal number

char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
char * pEnd; // pEnd不为null
long int li1, li2, li3, li4;
li1 = strtol (szNumbers,&pEnd,10); // 2001
li2 = strtol (pEnd,&pEnd,16); // 6340800
li3 = strtol (pEnd,&pEnd,2); // -3624224
li4 = strtol (pEnd,NULL,0); // 7340031

References: cplusplus official information
strtol function usage

to sum up:

1. These are commonly used when doing programming questions and processing input data and need to be kept in mind.

Guess you like

Origin blog.csdn.net/qq_33726635/article/details/107292795