【无标题】

C++字符串和数字相互转化

经常忘记,记录下来

#include<iostream>
#include<sstream>
#include<string>
using namespace std;

int main(){
    string s;
    int n;
    //方法1,使用stringstream,需包含头文件<sstream>
    //字符串->数字    double共保留6位
    stringstream ss,sss;
    cin >>s;
    ss << s;
    ss >> n;
    cout << typeid(n).name()<<" "<<n<<endl;
    double d;
    sss << s;
    sss >> d;
    cout << typeid(d).name()<< " " <<d<<endl;
    //数字->字符串
    stringstream its,dts;
    string is,ds;
    its <<n;
    dts <<d;
    its >>is;
    dts >> ds;
    cout << is+"/"+ds<<endl;
    //方法2,使用stoi,stod,stof等函数,需包含头文件<string>
    //字符串->数字
    cout << typeid(stoi(s)).name() <<" "<< typeid(stod(s)).name()<<" "<< typeid(stof(s)).name()<<endl;
    cout << stoi(s) <<" "<< stod(s)<<" "<<stof(s)<<endl;    //double和float共保留6位
    //方法3,使用to_string,需包含头文件<sstream>
    cout << to_string(n)+"/"+ to_string(d); //保留至小数点后6位
    return 0;
}

输入输出。

1234.5678987654
i 1234
d 1234.57
1234/1234.57
i d f
1234 1234.57 1234.57
1234/1234.567899
123456789.87654321
i 123456789
d 1.23457e+08
123456789/1.23457e+08
i d f
123456789 1.23457e+08 1.23457e+08
123456789/123456789.876543
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值