C ++では、char、char *、int、文字列変換関数、文字列変換関数

1. charからintおよびintからchar
1.1、charからint:

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

1.2、整数から文字へ:

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

2. charスター、charからストリングへ、およびstrngからcharスターへ、char
2.1、charスター、charからストリングへ:

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

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

2.2。strngを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およびstring to int
3.1、int to string:

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

3.2、intへの文字列:

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

4.異なる16進数(strtol)へ
文字列の関数プロトタイプ:

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

各パラメーターの意味:変換される
str文字
enptrは、最初の変換不可能な文字の位置へのポインターです:endptrがNULLでない場合、条件を満たさず終了した文字ポインターがendptrによって返されます; endptrがNULL、ポインタは返されません。
base10進数に変換された数値を意味する基数

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

参考資料:cplusplus公式情報
strtol関数の使用法

総括する:

1.これらは、プログラミングの質問や入力データの処理を行うときに一般的に使用されるものであり、留意する必要があります。

おすすめ

転載: blog.csdn.net/qq_33726635/article/details/107292795