views:

53

answers:

1

Okay, I am having trouble with the following piece of code (in a header file):

#ifndef XML_H_INCLUDED
#define XML_H_INCLUDED
#include "libxml/parser.h"
#include "libxml/xmlwriter.h"
#include <string>


class XmlFile{
public:
    XmlFile(string filename){
        file = xmlParseFile(filename);


    }
    xmlDocPtr file; //Pointer to xml file


};



#endif // XML_H_INCLUDED

The file is including in the main source file (but is not accessed, so its contents are not important).

I keep getting the following error (In Codeblocks):

error: cannot convert 'std::string' to 'const char*' 
for argument '1' to 'xmlDoc* xmlParseFile(const char*)'|

I have run into this many times, and it is driving me crazy.

I would prefer not to use vectors if possible (adds another step in initializing the function.

What am I doing wrong? I've tried looking this up, but have not found any satisfactory answers.

Thanks in advance.

+6  A: 
file = xmlParseFile(filename.c_str());
imaginaryboy
What exactly does that do? How does it work? Thanks.
Biosci3c
I should add that that line of code works fine, but I am curious as to what exactly it does (so I can avoid similar mistakes in the future). Is it simply a function defined in "String" that returns the string? How does it get around the const char* problem?
Biosci3c
@Biosci3c, std::string has a method c_str() which returns a const char*. The xmlParseFile expects a const char* (just like the compiler error says)...not a std::string.
dgnorton
It returns a `const char*` which points to the null-terminated sequences of characters that make up that string. A normal 'C' string, hence the name of the method.
imaginaryboy
Ah, thanks, makes sense. Ok, that answers my question. Wow, you guys are fast. :) Could have saved myself so much trouble earlier.
Biosci3c
dgnorton
@dgnorton, I don't need the string to be a constant, but it just seems to demand that I pass a const char*
Biosci3c
imaginaryboy
@Biosci3c, it's best practice to use `const` in that way. Don't have enough room in a comment to do the topic justice. Read up on it here ... [C++ FAQ Lite](http://www.parashift.com/c++-faq-lite/const-correctness.html). I would also suggest a couple books: ["Effective C++" by Scott Meyers](http://goo.gl/qtGF) and ["C++ Coding Standards" by Herb Sutter](http://goo.gl/AzfW).
dgnorton