C++ string、int和char的相互转换

首先,需要强调的是:0-9对应的ASCLL码值为48-57
其次,从string中访问得到的string[index]为char类型,用单引号’c’表示

1.char转int

用char减去’0’即可得到char对应的int值,char减去整数0得到其ASCII值。

int main() {
    char c = '1';
    cout << c - 0 << endl;//49
    cout << c - '0' << endl;//1

}

2.int转char

int值加上’0’,即可得到对应的char。

int main() {
    int i = 1;
    char c = i + '0';
    cout << c << endl;//'1'
}

3.char*转int

利用std::atoi()将char*转为int。

int main() {
	const char* s = "1234";
	int intS = atoi(s);
	cout << "char* 转int:    " << intS << endl;//1234
}

4.int转string

利用std::to_string可以实现int转string,to_string()只能将int类型转换为string,不能用于long类型

int main() {
    int i = 11111;
    string c = to_string(i);
    cout << c << endl;//"11111"
}

5.string转const char*

使用c_str()可以将string转为const char*。

c_str():生成一个const char*指针,指向以空字符终止的数组。

int main()
{
	//更好的方法是将string数组中的内容复制出来 所以会用到strcpy()这个函数
	char c[20];
	string s = "1234";
	// c_str()返回一个客户程序可读不可改的指向字符数组的指针,不需要手动释放或删除这个指针。
	strcpy(c, s.c_str());
	cout << c << endl;
	s = "abcd";
	cout << c << endl;
}

6.string转int

方法一

将string类型转为int类型,需先使用c_str()将string转为const char,之后调用std::atoi()将得到的const char*转换为int*。

int main() {
	string str("5678");
	//此写法会报错
	//int intStr = atoi(str);
	//需先将string转成char*
	int intStr = atoi(str.c_str());
	cout << "string 转int:    " << intStr << endl;//5678
}

方法二

直接调用stoi()函数。

int main() {
	string str("5678");
	int intStr = stoi(str);
	cout << "string 转int:    " << intStr << endl;//5678
}
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值