c/c++各种数据类型转换

本文介绍了使用C++进行不同类型数据转换的方法,包括字符到数字、数字到字符串、字符串到数字及字符到字符串的转换。重点推荐使用stringstream类简化转换过程。

1.字符转数字

char a = 'd';
char b = 'm';
int m;
m = a + b - '0';
cout << "m=" << m << endl;

2.数字转字符串

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<sstream>
using namespace std;

int main()
{
  stringstream ss;
  string s;
  int a = 12345;
  ss << a;
  ss >> s;        
}

3.字符串转数字

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<sstream>
using namespace std;

int main()
{
  stringstream ss;
  string s = “12345”;
  int a ;
  ss << s;
  ss >> a;        
}

4.字符转字符串

#include<iostream>
using namespace std;

int main()
{
  char ch = 'a';
  char s[2] = {ch, 0};
  string s1 = s;      
}

重推stringstream类

out_type change(in_type t)
{
  stringstream ss;
  ss << t;  //向流中传值
  out_type result;  //存储转化结果
  ss >> result; //将结果写入result return result; 
  return result;
}

 

 

 

转载于:https://www.cnblogs.com/QQ1171492144/p/8371718.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值