to_string、atoi/stoi、数字与字符的转换

#include <iostream>
#include<cstring>
using namespace std;
int main()
{
	//(1)0-9与‘0’-'9'的转化
	char ch = '2';
	int a = (int) ch;//此时a为ch的ASCII码值50,a=50
	int b = ch - '0';//b=2
	//int f = atoi(ch.c_str());
	//int f = atoi(ch);//这两种写法均是错误的
	cout<<a<<"\t"<<b<<endl; //a=50, b=2

	//(2)to_string: 将数值类型转化为字符串类型
	int temp1 = 2;
	double temp2 = 3.14;
	char ch1 = temp1 + '0',ch2 = temp2 + '0'; //整型数(0-9)转化为对应字符,ch1 = '2'
	string ch3 = to_string(temp1);//使用to_string函数也可以,但此时是字符传"2"
	string ch4 = to_string(temp2);
	cout<<ch1<<"\t"<<ch2<<"\t"<<ch3<<"\t"<<ch4<<endl;
	// ch1='2', ch2="3",ch3 = "2",ch4="3.140000",ch1是字符,ch2是字符串
	
	/*(3)stoi和atoi
	*atoi()的参数是 const char* ,因此对于一个字符串str我们必须调用 c_str()的方法把这个string转换成 const char类型的,
	*而stoi()的参数是const string,不需要转化为 const char*;
	*/		
	string s1("1234567");
	char s2[9] = "12345678";
	int c = stoi(s1);//1234567
	int d = atoi(s2);//12345678
	int e = atoi(s1.c_str());//1234567
	cout << c <<"\t"<<d<<"\t"<<e<< endl;
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值