C++中常用字符和数字转换函数整合

由于最近在刷题时碰到许多这样的问题,写个博客自己整理下

  1. 字符串型数字转纯数字
    例:“1234”->1234
  • atoi+c_str()
    代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
    string s="1234";
    int a= atoi(s.c_str());
    cout<<a<<endl;
}

输出:1234

  • stoi函数
    代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
    string s="1234";
    int a= stoi(s);
    cout<<a<<endl;
}

输出:1234

区别:

一、atoi()的参数是 const char* ,因此对于一个字符串str我们必须调用
c_str()的方法把这个string转换成 const char*类型的,stoi()的参数
是const string*,不需要转化为 const char*;

二、stoi()会做范围检查,默认范围是在int的范围内的,如果超出范围的
话则会runtime error!而atoi()不会做范围检查,如果超出范围的话,
超出上界,则输出上界,超出下界,则输出下界;
  1. 字符型数字转纯数字
    例:‘9’->9
  • ASCII码转换
    代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
    char s='9';
    int a=s-'0';
    cout<<a<<endl;
}

输出:9

  1. 数字转字符串(可以是double类型)
  • sstrem输入输出流
    代码:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    double  x=3.14159;
    string str;
    stringstream ss;
    //将double类型的值放入输入流中
    ss << x;
    //从sstream中抽取前面插入的int类型的值,赋给string类型
    ss >> str;
    cout <<str<<endl;
    if (typeid(str) == typeid(string))
        cout<<"str已转为字符串"<<endl;
    return 0;
}

输出:

3.14159
str已转为字符串
  • to_string方法,浮点数会附带小数点后六位,不足补零

代码:

#include <iostream>
#include<string>
using namespace std;
int main()
{
    double x=3.14159;
    string str;
    str = to_string(x);
    cout << str;
    return 0;
}

输出:3.141590

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值