Difference between #define and string?

Hi,

I would like to check what is the difference between #Define and string declaration when it come to myfile.open().
I'm able to compile successfully using the 1st program, however an "error C2664"
occurs when I try to run the 2nd program.

//1st Program
#define FileName "P09.txt"

int main() {
ifstream myfile;
myfile.open(FileName); .
.
.
.


//2nd Program
int main()
{
string FileName="P09.txt";
ifstream myfile;
myfile.open(FileName);
.
.
.
#define FileName "P09.txt" is resolved by the preprocessor which replaces FileName with the literal "P09.txt" string FileName="P09.txt"; declares a std::string object.

The problem is that with the current standard, istream::open takes a const char* argument ( the type of a string literal ), not a std::string.
You can however call string::c_str: myfile.open(FileName.c_str()); // 2nd program
avoid #defines whenever you can, they're unpredictable
Topic archived. No new replies allowed.