本文介绍了我如何检查流读取已经消耗了所有输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的函数,我尝试看看,如果一个字符串取值是敞篷通过查看键入 T 我可以读一个类型 T ,如果输入被完全消耗之后。我想

In the following function, I try to see if a string s is convertible to type T by seeing if I can read a type T, and if the input is completely consumed afterwards. I want

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;
}

然而, can_be_converted_to&LT;布尔&GT;(真)计算结果为假,因为 i.eof()就是在函数的最后假的。

However, can_be_converted_to<bool>("true") evaluates to false, because i.eof() is false at the end of the function.

这是正确的,即使功能已经阅读整个字符串,因为它并没有试图读取的过去的是字符串的结尾。 (因此,显然此功能适用于int和double因为 istringstream 读这些的时候读取过去的结束)。

This is correct, even though the function has read the entire string, because it hasn't attempted to read past the end of the string. (So, apparently this function works for int and double because istringstream reads past the end when reading these.)

因此​​,假设我的确应该检查(我和&lt;输入完全消耗&GT;)

So, assuming that I should indeed be checking (i and <input completely consumed>):

问:我如何检查输入被完全消耗W / O使用EOF()

Q: How do I check that the input was completely consumed w/o using eof()?

推荐答案

使用的或的检查什么是流中下一个:

Use peek() or get() to check what's next in the stream:

return (i >> std::boolalpha >> t && i.peek() == EOF);

您版本不适用整数的工作,无论是。考虑此输入: 123 45 。它会读123和报告真实,即使仍有留在流中的某些字符。

Your version doesn't work for integers, either. Consider this input: 123 45. It'll read 123 and report true, even though there are still some characters left in the stream.

这篇关于我如何检查流读取已经消耗了所有输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:48