2

首先,我知道 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
}

有没有更好的方法来检查并确保错误状态是由于溢出而不是其他问题?

4

1 回答 1

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
}

有没有更好的方法来检查并确保错误状态是由于溢出而不是其他问题?

不,不是。您必须知道哪些操作会导致哪些错误,并进行处理。关于异常的好处是

  • 你不能忽视它们。
  • 您不必在错误发生的地方处理错误。
于 2013-05-23T18:36:20.177 回答