Ben*_*nRI 5 c++ boolean eof istringstream
在下面的函数中,我尝试通过查看是否可以读取类型以及之后是否完全消耗输入来查看字符串s是否可转换为类型.我想要TT
template <class T>
bool can_be_converted_to(const std::string& s, T& t)
{
std::istringstream i(s);
i>>std::boolalpha;
i>>t;
if (i and i.eof())
return true;
else
return false;
}
Run Code Online (Sandbox Code Playgroud)
但是,can_be_converted_to<bool>("true")计算结果为false,因为i.eof()在函数结束时为false.
这是正确的,即使功能已经阅读整个字符串,因为它并没有试图看过去的字符串的结尾.(所以,显然这个函数适用于int和double,因为istringstream在阅读这些函数时会读到结尾.)
所以,假设我确实应该检查(i and <input completely consumed>):
问:如何使用eof()检查输入是否完全消耗?
return (i >> std::boolalpha >> t && i.peek() == EOF);
Run Code Online (Sandbox Code Playgroud)
您的版本也不适用于整数.考虑这个输入:123 45.它会读取123并报告为true,即使流中仍有一些字符.
| 归档时间: |
|
| 查看次数: |
390 次 |
| 最近记录: |