[C++] string转为int, float, double

    在使用C++编程过程中,string转为int, float, double是极为常见的操作,本文进行必要的总结,以供参考。

第一种方法:使用对应的函数

    使用atoi()、 atil() 、atof()函数 进行转换,其中atoi()是将string转为int型,atol()是将string转为long int型,atof()是将string转为double型。注意一点:atof()并不会将string转为float型,再转为double型后可以强制转换为float型。具体代码如下所示:

#include <iostream>
#include <windows.h>
#include <string>
int main()
{
    std::string getdata = "1234";
    int n_Val = std::stoi(getdata);
    int l_Val = std::stoi(getdata);
    std::cout << n_Val << std::endl;
    std::cout << l_Val << std::endl;
    
    std::string getdata = "1234.000";
    int d_Val = std::stof(getdata);
    std::cout << d_Val << std::endl;
    
    system("pause");  
    return 0;
}

第二种方法:使用stringstream

    此方法即使用istringstream 函数进行数据的转换。此方法适用性较强,作者一般使用此种方法。

#include <iostream>  
#include <sstream>    //使用stringstream需要引入这个头文件  
using namespace std;  

int main()
{
    int a;
    float b;
    string a_str = "123";
    string b_str = "333.2";

	istringstream isa_str(a_str);
	isa_str >> a;
	istringstream isb_str(b_str);
	isb_str >> b;

    cout << a << " " << b << endl;
    return 0;
}
  • 2
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

gz7seven

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值