是否有标准库函数来检查字符串S是否为T类型,因此可以将其转换为类型T的变量?检查字符串是否属于T类型C++ 11
我知道存在istringstream STL类,它可以使用运算符>>来填充T类型的变量,并使用从字符串转换而来的值。但是,如果字符串内容不具有类型T的格式,它将被填充为无意义。
是否有标准库函数来检查字符串S是否为T类型,因此可以将其转换为类型T的变量?检查字符串是否属于T类型C++ 11
我知道存在istringstream STL类,它可以使用运算符>>来填充T类型的变量,并使用从字符串转换而来的值。但是,如果字符串内容不具有类型T的格式,它将被填充为无意义。
你能做的就是尝试和失败,因为@Cameron评论最好:
#include <string>
#include <sstream>
#include <boost/optional.hpp>
template <typename T>
boost::optional<T> convert(std::string const & s)
{
T x;
std::istringstream iss(s);
if (iss >> x >> std::ws && iss.get() == EOF) { return x; }
return boost::none;
}
,或在不提升:
template <typename T>
bool convert(std::string const & s, T & x)
{
std::istringstream iss(s);
return iss >> x >> std::ws && iss.get() == EOF;
}
用法:
第一版本:
if (auto x = convert<int>(s))
{
std::cout << "Read value: " << x.get() << std::endl;
}
else
{
std::cout << "Invalid string\n";
}
第二个版本:
{
int x;
if (convert<int>(s, x))
{
std::cout << "Read value: " << x << std::endl;
}
else
{
std::cout << "Invalid string\n";
}
}
注意boost::lexical_cast
基本上是这样一个聪明版本,其声称是非常有效的(潜在moreso比使用输入输出流无条件正如我们在这里所做的)。
没有标准库函数。看它是否是成功的,你应该检查从operator>>
返回:
std::istringstream iss(mystring);
// if you want trailing whitespace to be invalid, remove std::ws
if((iss >> myT >> std::ws) && iss.eof())
{
// success
}
else
{
// failed
}
'如果字符串内容不具有类型T的格式,它将被无意义填充。这是因为它是未初始化的。 –
字符串没有类型。你可以做的最好的事情是猜测,使用类似['boost :: lexical_cast'](http://www.boost.org/doc/libs/1_51_0/doc/html/boost_lexical_cast.html) – Cameron