wro*_*ame 10 c++ string double
我想看看一个字符串是否包含double作为其唯一内容.换句话说,如果它可能是以下函数的输出:
string doubleToString(double num)
{
stringstream s;
s << num;
return s.str();
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*rle 11
你想要strtod功能.
bool isOnlyDouble(const char* str)
{
char* endptr = 0;
strtod(str, &endptr);
if(*endptr != '\0' || endptr == str)
return false;
return true;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Boost lexical_cast
来检查字符串是否包含double.
#include <boost/lexical_cast.hpp>
....
using boost::lexical_cast;
using boost::bad_lexical_cast;
....
template<typename T> bool isValid(const string& num) {
bool flag = true;
try {
T tmp = lexical_cast<T>(num);
}
catch (bad_lexical_cast &e) {
flag = false;
}
return flag;
}
int main(){
// ....
if (isValid<double>(str))
cout << "valid double." << endl;
else
cout << "NOT a valid double." << endl;
//....
}
Run Code Online (Sandbox Code Playgroud)
您已经获得了C风格和提升替代方案,但是以您的doubleToString
实施方式:
bool is_double(const std::string& s)
{
std::istringstream iss(s);
double d;
return iss >> d >> std::ws && iss.eof();
}
Run Code Online (Sandbox Code Playgroud)
在这里,您正在检查iss >> d
返回iss
,true
如果流式传输成功,它将仅在布尔上下文中求值.除了空格之外什么都没检查eof()
确保没有尾随垃圾.
如果你想考虑前导和尾随空白垃圾:
return iss >> std::nowkipws >> d && iss.eof();
Run Code Online (Sandbox Code Playgroud)
这可以推广到类似于boost的布尔返回测试lexical_cast<>
......
template <typename T>
bool is_ws(const std::string& s)
{
std::istringstream iss(s);
T x;
return iss >> x >> std::ws && iss.eof();
}
template <typename T>
bool is(const std::string& s)
{
std::istringstream iss(s);
T x;
return iss >> std::noskipws >> x && iss.eof();
}
...
if (is<double>("3.14E0")) ...
if (is<std::string>("hello world")) ...; // note: NOT a single string
// as streaming tokenises at
// whitespace by default...
Run Code Online (Sandbox Code Playgroud)
您可以针对任何类型特定的行为专门化模板,例如:
template <>
bool is<std::string>(const std::string& s)
{
return true;
}
Run Code Online (Sandbox Code Playgroud)