linux g++ 下C++ int,char,string 转换注意

int 与 char 互转

说明:int与char的转换是指依照ASCII字符集的映射关系转换,很简单c++默认的赋值就可以转换;

贴一个简单的测试程序

  3 #include <iostream>
  4 #include <typeinfo>
  5 #include <string>
  6 
  7 using namespace std;
  8 
  9 int main(int argi, char* argc[])
 10 {
 16         //int -- char
 17         int inta = 49;
 18         char chara='a';
 19         string stra = "98";
 20 
 21         char charb= inta;
 22         int intb = chara;
 23 
 24         //int -- string;
 25         string strc = to_string(inta);                            
 26         int intc = stoi(stra);
 27         
 28         cout <<"int 与 char 直接转换 :"<<endl;
 29         cout <<"charb type : "<<typeid(charb).name() << "----值 :     "<<charb <<endl;
 30         cout <<"intb type : "<<typeid(intb).name() << "----值 : "<    <intb <<endl;
 31         cout <<"------------------------------------"<<endl;
 32 
 33         cout <<"int 与 string 类型转换 : "<< endl;
 34         cout <<"strc type : "<<typeid(strc).name() << "----值 : "<    <strc <<endl;
 35         cout <<"intc type : "<<typeid(intc).name() <<"----值 : " <    <intc <<endl;
 36 
 37         return 0;
 38 }
//运行结果:
int 与 char 直接转换 :
charb type : c----值 : 1
intb type : i----值 : 97
------------------------------------
int 与 string 类型转换 : 
strc type : Ss----值 : 49
intc type : i----值 : 98

int 与 string 互转方法有很多,这里不介绍stringstream

简单的说说在std空间中的to_string 和stoi两函数的使用注意点:

首先.这两函数都是C++11后支持的,所以要确保自己gcc++版本支持
其次.是即使gcc版本支持,默认编译时也是用的c++98的版本,所以记得编译时

带上 “-std=c++11”,我这里为了一劳永逸取了别名:alias g++11=“g++ -std=c++11”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值