1,105,585 Community Members

string to double

Member Avatar
kimw
Newbie Poster
22 posts since Oct 2005
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
2
 

i have a string that i want to convert to double. i know atof is a standard library function for that, however, the input argument to atof is (const char*), not string type that i have.

does anyone know how i might convert my string num to double ? thanks

string num = "45.00";
double x = atof(num);
Member Avatar
Grunt
Junior Poster
147 posts since Jul 2006
Reputation Points: 19 [?]
Q&As Helped to Solve: 12 [?]
Skill Endorsements: 0 [?]
 
3
 

You can use istringstream

std::istringstream stm;
stm.str("3.14159265");
double d;
stm >>d;
Member Avatar
WolfPack
Posting Virtuoso
1,787 posts since Jun 2005
Reputation Points: 491 [?]
Q&As Helped to Solve: 135 [?]
Skill Endorsements: 15 [?]
Moderator
 
1
 

If you are sure that the string is in double conversible format like 1.2e-2, grunt's method is the eaisest. But if you want to check the input string if it can be converted as double, e.g 123abc will be converted as 123 in grunt's method. For easier error checking better use strtod. Just checking the value of end to be null will be enough.

#include <sstream>
#include <cstdlib>
int main ()
{
    std::istringstream stm;
    char* end = 0 ;
    
    double d;
    
     stm.str("123abc");// Invalid input string
    stm >>d;  
     std::cout << d << std::endl; // Returns 123
     
    stm.str("123e-2");
    stm >>d;  
    std::cout << d << std::endl;  

     d = strtod( "123abc", &end ); // Invalid input string
     if ( *end == 0 )
        std::cout << d << std::endl;
    else
         std::cout << "Error Converting\n"; // Reports error
         
    d = strtod( "123e-2", &end );
    if ( *end == 0 )
        std::cout << d << std::endl;
    else
        std::cout << "Error Converting\n";
        
    return 0;
}

PS:
To get the characters from num , use num.c_str()

Member Avatar
kimw
Newbie Poster
22 posts since Oct 2005
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

thank you all. for the time being my strings are all convertible to double. but i might need wolfpack's suggestion just to be safe

Member Avatar
Grunt
Junior Poster
147 posts since Jul 2006
Reputation Points: 19 [?]
Q&As Helped to Solve: 12 [?]
Skill Endorsements: 0 [?]
 
0
 

If you want error checking then I would suggest you to use Exception Handling. That will be a better option.

Member Avatar
Dave Sinkula
long time no c
4,852 posts since Apr 2004
Reputation Points: 2,398 [?]
Q&As Helped to Solve: 340 [?]
Skill Endorsements: 69 [?]
Team Colleague
 
2
 
You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article