c++stringpointersmfcfilestreams

C++ File Write includes the memory address of the string instead of the contents


All, I'm still learning C++ but I have an issue in a project I'm tinkering with that I'm curious about. I've noticed that when I try to print the contents of a string that is a member of a class, I get the memory address instead of the contents. I understand that this is because the item is a pointer, but what I"m confused about is that I am using the -> operator to deference it.

Why can I evaluate the class member in an if statement using the -> operator to dereference it but when printing to a file string in the same manner I get the memory address instead?

An example is below:

Lets say I have a class called pClass with a member called m_strEmployeeName. As a side note (I don't know if it matters), the m_strEmployeeName value is CString rather than std::string, so there could be some unknown conversion issue possibly as well.

If I used the following simple code, I get a memory address.

std::ofstream file("testfile.text");
file << pClass->m_strEmployeeName;
file.close();

I get the same behavior with the following dereferencing method (which I would expect since -> is the same thing).

std::ofstream file("testfile.text");
file << (*pClass).m_strEmployeeName;
file.close();

Any idea on what I'm doing wrong?


Solution

  • It is because your CString class is actualy CStringW class wich contain wchar_t strings so std::ofstream not contain operator >> overload that support wchar_t* strings. To print CStringW class objects you may use this type of stream std::wofstream it recognize wchar_t* strings properly and output will be right.

    std::wofstream file("testfile.text");
    file << pClass->m_strEmployeeName;
    file.close();
    

    You may also create your program in multibyte character support. It can be specified in your project settings. But I suggest you to stay with UNICODE.