c++ string与int(其他的内部类型)转换

一、int转string

1.如果你用的编译器是基于最新的C++11标准,那么string和其他类型转换问题就变的很简单,因为中已经封装好了对应的转换方法:

标准库中定义了to_string(val);可以将其它类型转换为string。

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val)

2.采用sstream中定义的字符串流对象来实现

ostringstream os; //构造一个输出字符串流,流内容为空   
int i = 12;   
os << i; //向输出字符串流中输出int整数i的内容   
cout << os.str() << endl; //利用字符串流的str函数获取流中的内容   

二、string转int

1.C++11还定义了一组stoi(s,p,b)、stol(s,p,b)、stod(s,p,b)等转换函数,可以分别转化成int、long、double等. 在头文件<string>

stoi(s,p,b);stol(s,p,b);stoul(s,p,b);stoll(s,p,b);stoull(s,p,b);返回s的起始子串(表示整数内容的字符串)的数值,返回值的类型分别为:int、long、unsigned long、long long、unsigned long long.其中b表示转换所用的基数,默认为10(表示十进制).p是size_t的指针,用来保存s中第一个非数值字符的下标,p默认为0,即函数不返回下标.

stof(s, p); stod(s, p); stold(s, p); 返回s的起始子串(表示浮点数内容)的数值,返回值的类型分别是float、double、long double.参数p的作用与整数转换函数中的一样。

非数字开头的会抛出std::invalid_argument异常。

#include <iostream>
#include <string>


int main()
{
    std::string a = "a123asd";
    int i = std::stoi(a);//std::invalid_argument异常
    std::cout << i << std::endl;
    getchar();
    return 0;
}

2.2.采用标准库中atoi函数,对于其他类型也都有相应的标准库函数,比如浮点型atof(),long型atol()等等.在头文件<cstdlib>

string s = "12";   
int a = atoi(s.c_str());  

3.采用sstream头文件中定义的字符串流对象来实现转换

istringstream is("12"); //构造输入字符串流,流的内容初始化为“12”的字符串   
int i;   
is >> i; //从is流中读入一个int整数存入i中  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值