C++ C++;:使用boolalpha
我正在使用一个函数(TinyXML的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>
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::couttixmlement::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