1

I am trying to write a cstring to a file, but have so far been unsuccessfull. I have tried the following:

std::ofstream myfile;
myfile.open(Placering, std::ofstream::out);
myfile << output;
myfile.close();

This however just seems to print the address of "output" to "myfile".

I then tried

for(int i = 0; i < output.getlength(); i++){
    myfile << output[i]
}

for every element in output, but that seems to just print the ASCII value of the characters to "myfile".

How do i correctly write my CString to a file? The content of the CString file can be HTML and rtf code.

EDIT: I found a solution, by casting the CString to a CStringA

std::ofstream myfile;
CStringA output = T2A(stringtoprint);
myfile.open(filename, std::ofstream::out);
for(int i = 0; i < output.GetLength(); i++){
    myfile << output[i];
}
myfile.close();
stefan
  • 195
  • 1
  • 13
  • If this is a UNCODE build, [look at this answer](http://stackoverflow.com/a/7500209/2065121) to find out about BOM. – Roger Rowland Nov 25 '13 at 08:06
  • I'am afraid i don't understand much of what is going on in the answer you linked to. I am very new to C++. – stefan Nov 25 '13 at 08:33
  • 1
    If you are building a Unicode build (as seems likely), then `CString` represents an array of `wchar_t`, not an array of `char`. In which case you need to write it to `wofstream`, not `ofstream`. – Igor Tandetnik Nov 25 '13 at 15:36
  • Thanks for your help. I found another solution, which i have described in my original post. – stefan Nov 26 '13 at 07:16

2 Answers2

1

I found a solution, by casting the CString to a CStringA

myPrintMethod(CString stringtoprint, LPCWSTR myfile){
    std::ofstream myfile;
    CStringA output = T2A(stringtoprint);
    myfile.open(filename, std::ofstream::out);
    for(int i = 0; i < output.GetLength(); i++){
        myfile << output[i];
    }
    myfile.close();
}
stefan
  • 195
  • 1
  • 13
1

I found a different solution

myPrintMethod(CString stringtoprint, LPCWSTR myfile){
std::ofstream myfile;
myfile.open(filename, std::ofstream::out);
myfile << CT2A(stringtoprint);
myfile.close();

}

Arif_Khan
  • 31
  • 4