数字字符串互相转换的三种方法

数字字符串互相转换的三种方法

在刚学C++的时候,只会用itoa()atoi()进行字符串与数字之间的转换,这种方法不仅麻烦,而且很容易出错。
现在介绍三种方法,可以更方便的进行字符串与数字的转换。

stringsteam

需要引入sstream头文件

stringsteam ss;
string s;
int a = 123;
ss << a; // 把a存入到ss里面
ss >> s; // 把ss中的数据取出到s里

stringint同理。
不过使用这种方法进行转换会慢一点,对速度有要求的可以往下看。

ASCII码转换

char转int

char c = '2';
int n = (int)c - '0'; // 把c强制转换为int的ASCII码形式,再减去'0'即可转换为数字('0'的ASCII码为48)

如果是字符串的话可以使用strlen()函数进行for循环进行累加

char s[3] = "233";
int n;
for (int i = 0; i < strlen(s); i++) {
    n += s[i] - '0';
    n *= 10; // 进位
}

int转char

int n = 2;
char c = n + '0'; // n加上46即可得到n的ASCII码

int转字符串的话可以把上面的方法反过来就可以了。

sprintf和sscanf

int num = -150;
char str[128];
int rsl;
sprintf(str, "%d", num); // 数字转字符串
sscanf(str, "%d", &rsl); // 字符串转数字
posted @ 2020-05-08 10:44  RainbowBird  阅读(1095)  评论(0编辑  收藏  举报