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
2,062 posts since Jun 2005
Reputation Points: 572
Solved Threads: 119
Skill Endorsements: 11
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
Skill Endorsements: 38