开发者

C++: Using boolalpha

I am using a function (TinyXML's TiXmlElement::QueryValueAttribute(const std::string &name, T * outValue) that attempts to read a string into the data type that is passed. In my case I am passing a bool. So I want to use the boolalpha flag so that the input can be true 开发者_运维技巧or false instead of 0 or 1.

How do I do this?

Thanks.


TiXmlElement::QueryValueAttribute uses a std::istringstream to parse the value. So, you can create a wrapper class around bool that overloads operator >> to always set boolalpha before extraction:

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


You can use the string value to construct a istringstream, then stream from there into your *T variable. The I/O aspects are illustrated below.

#include <iostream>                                                             
#include <iomanip>                                                              
#include <sstream>                                                              

int main()                                                                      
{                   
    // output example                                                            
    std::cout << std::boolalpha << true << ' ' << false << '\n';

    // input example                
    std::istringstream iss("true false");                                       
    bool x = false, y = true;                                                   
    iss >> x >> y;                                                              
    std::cout << std::boolalpha << x << ' ' << y << '\n';                       
}


You could just use

std::cout << std::boolalpha;

in main().

For example

int main()
{
    std::cout << std::boolalpha;
    int x {1};
    int y {2};
    bool z = y < x;
    std::cout << z << std::endl;
    
    return 0;
}

The output will be false instead of 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜