We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,414 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

string to double

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);
4
Contributors
5
Replies
8 Hours
Discussion Span
6 Years Ago
Last Updated
7
Views
kimw
Newbie Poster
22 posts since Oct 2005
Reputation Points: 44
Solved Threads: 0
Skill Endorsements: 0

You can use istringstream

std::istringstream stm;
stm.str("3.14159265");
double d;
stm >>d;
Grunt
Junior Poster
152 posts since Jul 2006
Reputation Points: 197
Solved Threads: 12
Skill Endorsements: 0

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()

WolfPack
Postaholic
Moderator
2,062 posts since Jun 2005
Reputation Points: 572
Solved Threads: 119
Skill Endorsements: 11

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

kimw
Newbie Poster
22 posts since Oct 2005
Reputation Points: 44
Solved Threads: 0
Skill Endorsements: 0

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

Grunt
Junior Poster
152 posts since Jul 2006
Reputation Points: 197
Solved Threads: 12
Skill Endorsements: 0
Dave Sinkula
long time no c
Team Colleague
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
Skill Endorsements: 38

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0735 seconds using 2.78MB