C++:使用 boolalpha

标签 c++ io inputstream boolean

我正在使用一个函数(TinyXML 的 TiXmlElement::QueryValueAttribute(const std::string &name, T * outValue)尝试将字符串读入传递的数据类型。在我的例子中我正在传递一个 bool。所以我想使用 boolalpha 标志,以便输入可以是 truefalse 而不是 01

我该怎么做?

谢谢。

最佳答案

TiXmlElement::QueryValueAttribute 使用 std::istringstream 来解析值。因此,您可以围绕 bool 创建一个包装类,重载 operator >> 以在提取之前始终设置 boolalpha:

class TinyXmlBoolWrapper
{
public:
    TinyXmlBoolWrapper(bool& value) : m_value(value) {}

    bool& m_value;
};

std::istream& operator >> (std::istream& stream, TinyXmlBoolWrapper& boolValue)
{
    // Save the state of the boolalpha flag & set it
    std::ios_base::fmtflags fmtflags = stream.setf(std::ios_base::boolalpha);
    std::istream& result = stream >> boolValue.m_value;
    stream.flags(fmtflags);  // restore previous flags
    return result;
}

...

bool boolValue;
TinyXmlBoolWrapper boolWrapper(boolValue);
myTinyXmlElement->QueryAttribute("attributeName", &boolWrapper);
// boolValue now contains the parsed boolean value with boolalpha used for
// parsing

关于C++:使用 boolalpha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4789193/

相关文章:

c++ - 在 operator[] 中混合引用和值行为

c++ - C++随机数生成与Python的区别

c++ - LONG_MAX 的 fseek 错误

Java nio 连接正在创建多个套接字级连接,为什么?

尝试将输入流复制到输出流时发生 Java IOException

python - 在 python 中读取音频流

java - 未编译 "base operand of ‘->’ 的 JNI IMU 代码具有非指针类型 ‘JNIEnv’“

java - 如何减少 System.out.println() 所花费的时间;

python-2.7 - pickle 中 io 与字符串内容的不同行为

java - 读取守护进程的输入流导致程序卡住