如何检查ostrstream是否已满?

时间:2013-05-23 18:26:35

标签: c++ stream

首先,我知道ostrstream已被删除,但在这种情况下,重构为ostringstream并不是一个真正的选择。

目前,我只是在<<操作后检查流是否设置了错误位:

示例(是的,非常简化):

char* buf = new char[10];
std::ostrstream tempOut(buf, 10);

tempOut << "To many charactors to fit in the buffer";

if (tempOut.bad()) {
   // Do what needs to be done to allocate a bigger buf
}

有没有更好的方法来检查确定坏状态是因为溢出而不是其他问题?

1 个答案:

答案 0 :(得分:4)

  

有没有更好的方法来检查确定坏状态是因为溢出而不是其他问题?

调用exceptions()方法设置将抛出哪些异常。这是处理错误的正确c ++方式。您必须在知道如何解决错误的地方处理异常。

所以,我会这样做:

char* buf = new char[10];
std::ostrstream tempOut(buf, 10);
tempOut.exceptions(std::ios::badbit);

try
{
tempOut << "To many charactors to fit in the buffer";
}
catch( const std::exception & e )
{
  //resolve error
}

  

有没有更好的方法来检查确定坏状态是因为溢出而不是其他问题?

不,不是真的。您必须知道哪个操作可能导致哪些错误并处理它。关于例外的好事是

  • 你不能忽视它们。
  • 您不必在发生错误的地方处理错误。
相关问题