Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;:使用boolalpha_C++_Io_Inputstream_Boolean - Fatal编程技术网

C++ C++;:使用boolalpha

C++ C++;:使用boolalpha,c++,io,inputstream,boolean,C++,Io,Inputstream,Boolean,我正在使用一个函数(TinyXML的tixmlement::queryvalue属性(const std::string&name,T*outValue)它试图将字符串读入所传递的数据类型。在我的例子中,我传递的是bool。因此我想使用boolalpha标志,以便输入可以是true或false,而不是0或1 我该怎么做 谢谢。您可以使用字符串值来构造istringstream,然后从那里流到您的*T变量中。I/O方面如下所示 #include <iostream>

我正在使用一个函数(TinyXML的
tixmlement::queryvalue属性(const std::string&name,T*outValue
)它试图将字符串读入所传递的数据类型。在我的例子中,我传递的是
bool
。因此我想使用
boolalpha
标志,以便输入可以是
true
false
,而不是
0
1

我该怎么做


谢谢。

您可以使用字符串值来构造istringstream,然后从那里流到您的*T变量中。I/O方面如下所示

#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';                       
}
#包括
#包括
#包括
int main()
{                   
//输出示例

std::cout
tixmlement::QueryValueAttribute
使用
std::istringstream
解析值。因此,您可以在
bool
周围创建一个包装类,该类重载
操作符>
,以便在提取之前始终设置
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