C++string类型和int类型的相互转换

string 转换到int型

如果转换的是单个数字

   string s = "1234";
    s += "null";
    std::cout << s[1] << std::endl; //用[]重载得到的元素是char类型的一个元素
    auto b = s[1];//得到一个字符
    std::cout <<typeid(b).name()<< std::endl;
    int c = b - '0'; //'1'通过减去'0'的字符可以自动转到int; 

同时转换多位数字

  • 使用stoi(),注意接受的参数类型是string
string s = "1234";
int i_from_s = stoi(s);
  • atoi() ,注意接受的参数类型是const char*
int i_from_s = atoi(s.c_str());//如果直接放s就会出错


int型转换到string

string to_string (int val);

int i=123;
string s=to_string(i);

补充:使用数据流进行转换
相比c库的转换,它更加安全,自动和直接。

#include <string>
#include <sstream>
#include <iostream> 

int main()
{
    std::stringstream stream;
    std::string result;
    int i = 1000;
    stream << i; //将int输入流
    stream >> result; //从stream中抽取前面插入的int值
    std::cout << result << std::endl; // print the string "1000"
} 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值