如何将 std::string 转 int,double (C/C++) (C) (template)

2019-10-0915:52:21来源:真 OO无双 评论 1,028 views

Abstract
std::string为library type,而int、double为built-in type,两者无法利用(int)或(double)的方式互转,本文提出转換的方式。

Introduction
使用环境:Visual C++ 9.0 / Visual Studio 2008

Method 1:

使用C的atoi()與atof()。

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

string_to_double.cpp / C++

/*
(C) OOMusou 2008 http://oomusou.cnblogs.com

Filename    : string_to_double.cpp
Compiler    : Visual C++ 9.0 / Visual Studio 2008
Description : Demo how to convert string to int (double)
Release     : 08/01/2008 1.0
*/

#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++

/*
(C) OOMusou 2006 http://oomusou.cnblogs.com

Filename    : stringstream_to_double.cpp
Compiler    : Visual C++ 8.0
Description : Demo how to convert string to any type.
Release     : 11/18/2006
*/
#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;
}

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: