C++字符(串)与整数的转换相关用法

2021-08-10  本文已影响0人  random_walk

在刷题和写代码过程中经常会遇到,要将字符(串)转为对应的数字或者ASCII码,总结一下相关的用法。

char to int

转换成字符有两种情况,分别是转换成ASCII码和字符对应的整数,可以通过如下方法来完成:

    char c = '2';
    int x = int(c);  // get ASCII code
    int y = (int) c;
    int z = c - '0'; // get 2, equals to int (c) - int('0')

int to char

int n = 6;
char cn = n + '0';

int to string

std::to_string(i)

string to int

std::stoi
std::stol
std::stoll
std::stof
std::stod
std::stold
上一篇 下一篇

猜你喜欢

热点阅读