2014-12-20 53 views
0
bool win::checkIfFScreen(sf::RenderWindow &window) 
{ 
    TiXmlDocument doc; 
    TiXmlElement * fullscreen; 

    if(!doc.LoadFile("videoSettings.xml")) 
    { 
     fullscreen = new TiXmlElement("Window"); 
     fullscreen->SetAttribute("Fullscreen: ", 0); 
     doc.LinkEndChild(fullscreen); 
     fullscreen->Attribute("Fullscreen: "); 

     std::cout << typeid(*fullscreen->Attribute("Fullscreen: ")).name() << std::endl; 
     doc.SaveFile("videoSettings.xml"); 
     return false; 
    } 

    if(*(fullscreen->Attribute("Fullscreen: ")) == '0') 
     return false; 

    return true; 


} 

理念:TinyXML的不能比较属性为char

所以,我想约人的偏好存储信息,如果他想为游戏是全屏或窗口。我创建了这个布尔函数来检查是否存在“videoSettings.xml”文件并返回有关用户偏好的信息。如果文件不存在,它将在全屏设置为0时创建(基本上意味着游戏将被窗口化并且用户可以在游戏设置中稍后改变它)。

不起作用部分:

if(*(fullscreen->Attribute("Fullscreen: ")) == '0') 
    return false; 

添加此两行我有段错误后(核心转储)。

看来,该值存储为字符。

编辑: 这行解决了一切:)。

TiXmlHandle docHandle (&doc); 
TiXmlElement *child = docHandle.FirstChild("Window").ToElement(); 
if(child) 
    if(*child->Attribute("fullscreen") == '1') 
     return true; 
    else if(*child->Attribute("fullscreen") == '0') 
     return false; 

谢谢@frasnian。

+0

你确定首先你的代码输入第一个if case吗?首先尝试NULL情况,然后尝试这种情况下,如果案例 – Thellimist

+0

@ user140345:很高兴它帮助。但要注意的一点是,如果XML文档中不存在属性“全屏”,则对“Attribute”的调用将返回null。你会在你的'if(* child-> Attribute ...'test)中解引用一个nullptr,确保测试'Attribute()'的结果以确保它是一个有效的指针,然后将它解除值为 – frasnian

回答

1

你的代码有这样的:

TiXmlElement * fullscreen; // not initialized to anything here 

if(!doc.LoadFile("videoSettings.xml"))  // LoadFile returns true on success 
{ 
    fullscreen = new TiXmlElement("Window"); // okay 
     ... 
    return false; 
} 

// question: if doc.LoadFile() succeeds, what is this going to do- 
if(*(fullscreen->Attribute("Fullscreen: ")) == '0') 
    return false; 

您正在使用fullscreen之后以任何初始化。

上编辑 针对在评论质疑:

如果加载文档成功,你需要的东西,如获得根元素:

TiXmlElement* root = doc.FirstChildElement("Whatever"); // root element name 
if (root){ 
    TiXmlElement* el = root->FirstChildElement("Window"); // etc, etc, 

当你走过的文档层次结构到您的“Window”元素的任何位置,请使用TiXmlElement::Attribute()TiXmlElement::QueryAttribute()来获取属性的值(如果存在)。

比使用FirstChild/NextSibling等等(用TiXmlElementTiXmlNode继承)更好的方法是使用句柄。查看与TiXmlHandle相关的TinyXML文档 - 主文档页面有一个非常简单的例子。

作为便笺,应该删除发布代码中属性名称后的冒号(即"fullscreen",而不是"Fullscreen:")。

另外,该线路:

fullscreen->Attribute("Fullscreen: "); 

后立即打电话LinkEndChild()没有做任何事情。

+0

哦,我知道了,你知道吗,如果有什么东西可以从文件中获得属性? – user140345

+0

谢谢,我已经解决了! – user140345

+0

我忘了删除这行fullscreen-> Attribute(“Fullscreen:”); 当我在这里问问题时。我知道它没有做任何事情。 :) – user140345