istream提取没有明显原因地设置failbit



我正在创建一个基本类型包装器,它可以使用boost::lexical_cast从字符串设置其值。它工作得很好,但是由于某种原因std::istream提取操作符设置了failbit。下面的程序打印:

123.45
EXCEPTION: ios_base::failbit set

但是如果你注释掉"stream . net"这行。异常(…"它工作并打印:

123.45
123.45

无论是否使用unicode进行编译,或者使用int或float作为ValueType, failbit在任何情况下都会被设置。

#include <conio.h>
#include <exception>
#include <iostream>
#include <string>
#include <tchar.h>
#include <boost/lexical_cast.hpp>
#if defined(UNICODE) || defined(_UNICODE)
    typedef std::wstring    StringType;
    typedef std::wistream   IStreamType;
#else
    typedef std::string     StringType;
    typedef std::istream    IStreamType;
#endif

#if 1 // Use float
    typedef float           ValueType;
    #define VALUE_STRING    _T("123.45")
#else // Use int
    typedef int             ValueType;
    #define VALUE_STRING    _T("123")
#endif

struct Castable {
    ValueType m_val;
};
inline IStreamType& operator>> ( IStreamType& inStream, Castable& castable )
{
    inStream.exceptions( IStreamType::failbit | IStreamType::badbit );
    inStream >> castable.m_val;
    return inStream;
}

int _tmain(int argc, _TCHAR* argv[])
{
    try{
        StringType sVal = VALUE_STRING;
        ValueType val;
        val = boost::lexical_cast<ValueType>(sVal);
        std::cout << val << std::endl;
        Castable cst;
        cst = boost::lexical_cast<Castable>(sVal);
        std::cout << cst.m_val << std::endl;
    }catch( std::exception& ex ){
        std::cout << "EXCEPTION: " << ex.what() << std::endl;
    }
    _getch();
    return 0;
}

为什么std::istream会认为出错了?

这样做的一个原因可能是lexical_cast的实现可能故意尝试导致某些流失败,以便检查所有输入文本是否已被消耗。例如,一个简单的实现可能是这样的:

template <typename Target>
    Target lexical_cast(const string& s) {
    /* Insert the string into a stringstream to use extraction. */
    std::stringstream converter(s);
    /* Pull out an object of type Target, failing if we can't. */
    Target result;
    if (!(converter >> result)) throw bad_lexical_cast();
    /* To confirm that we read everything out of the stream, try pulling out a 
     * single character.  If we can do this, then there is something left in the
     * stream that wasn't picked up earlier and the input was malformed.
     */
    char ch;
    if (converter >> ch) throw bad_lexical_cast();
    return result;
}

这里的想法是,最后的检查试图打破流,看看是否有东西被留下。如果你启用异常,这将把一些应该是正常的流故障检测到failbit变成一个异常,这是代码没有预料到的。

一般来说,你不应该在提取例程中设置流设置。这取决于打电话的人。否则,无论您在调用提取例程之前尝试对流做什么,例程都会覆盖您的首选项。这将是糟糕的,毕竟,如果我显式禁用异常,然后有异常发生,因为你在operator >>内部打开它们。

希望这对你有帮助!

最新更新