++
, std::istringstream:
#include <sstream>
bool is_double(std::string const& str) {
std::istringstream ss(str);
{
double d;
ss >> d;
}
return (ss && (ss >> std::ws).eof());
}
, ( ):
- -, ,
operator>>. .- double,
abc, . , , 3abc, . - ,
ss , false. - , . ( ,
eof() true, . std::ws ), eof true. , , 3abc . && true, true , , .
, int . , , , . , , boost::lexical_cast. : http://www.boost.org/doc/libs/1_37_0/libs/conversion/lexical_cast.htm.
C Way One
(), ( , ):
#include <cstdlib>
#include <cctype>
bool is_double(std::string const& s) {
char * endptr;
std::strtod(s.c_str(), &endptr);
if(endptr != s.c_str())
while(std::isspace(*endptr)) endptr++;
return (endptr != s.c_str() && *endptr == '\0');
}
strtod endptr . . , endptr , strtod.
C
, std::sscanf . -. :
#include <cstdio>
bool is_double(std::string const& s) {
int n;
double d;
return (std::sscanf(s.c_str(), "%lf %n", &d, &n) >= 1 &&
n == static_cast<int>(s.size()));
}
std::sscanf , . , %n , . >=, (. sscanf). n . . .
, std::stringstream ++. , ++.