html 转化为double,C++中怎么进行string转化为double等类型转换

本文介绍了两种在C++中将字符串转换为整数和浮点数的方法。Method1利用C库函数atoi()和atof(),通过c_str()将std::string转换为C风格字符串进行转换。Method2则使用了std::stringstream,通过模板函数实现std::string到int和double的转换,更加灵活且易于扩展。
摘要由CSDN通过智能技术生成

Method 1: 使用C的atoi()和atof()。

先利用c_str()转成C string,再用atoi()与atof()。

#include

#include

#include

using namespace std;

int main() {

string s = "123";

double n = atof(s.c_str());

//int n = atoi(s.c_str());

cout << n << endl;

}

Method 2:

利用stringstream 这里使用functon template的方式将std::string转int、std::string转double。

stringstream_to_double.cpp / C++

#include

#include

#include

template

void convertFromString(T &, const std::string &);

int main() {

std::string s("123");

// Convert std::string to int

int i = 0;

convertFromString(i,s);

std::cout << i << std::endl;

// Convert std::string to double

double d = 0;

convertFromString(d,s);

std::cout << d << std::endl;

return 0;

}

template   void convertFromString(T &value, const std::string &s) {   std::stringstream ss(s);   ss >> value; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值