开发者

Char not being saved to file correctly

I want to save the contents of a ComboBox to a file. The code below correctly shows a MessageBox with "Marker 4" (the text in the ComboBox), but the saved file contains "03038D8C" instead of "Marker 4", I guess this is the memory address of the variable or something similar? How can I correctly output the "Marker 4"-string to the file?

private: System::Windows::Forms::ComboBox^  cmbMarker;
private: System::String^ strMarkerText; 

...

strMarkerText = this->cmbMarker->Text;

...

ofstream myfile;

WIN32_FIND_DATA data;
pin_ptr<const wchar_t> wname = PtrToStringChars(strMarkerText);
FindFirstFile(wname, &data);

::MessageBox(0, wname, L"Marker inserted", MB_OK);

myfile <<"=====MARKER '" << wname <开发者_如何学Python< "' INSERTED AT " << datetime << " =====" << endl;

[There may be more than this wrong with this snippet, I'm not from a C++/CLI background but appreciate your help! There are no compiler errors and the code runs fine except for the issue described above, i.e. that not the cleartext-string-contents are written to the file ("Marker 4"), but "03038D8C".]

Thanks,

Nick


The problem is that you're using a narrow stream with a wide string. Use std::wofstream instead of std::ofstream and it should work fine.

That being said, I agree with @jonsca -- why drag iostreams into a C++/CLI app?


I'm not sure of your application's requirements, but have you considered using the .NET "equivalents" of the functions, like System::IO::Directory methods (specifically GetFiles in place of FindFirstFile), and the System::IO::StreamWriter in place of the ofstream object? This way the code in this section jives with the CLR portion of your code.

I know that's not precisely what you were asking for, but I have a feeling that the pointer in your code might need to be handled differently, and I'm unsure if would have to be marshaled across the managed/unmanaged barrier.


I ended up converting the System::String^ to a std:str and directly inserted this (rather than converting it to a wchar_t).

The mix between native c++ and CLI is because I'm building on a SDK-example built in native c++, but wanted to add a form to it (in Visual Studio 2008), which turned it into this "mix". I realize that that's not optimal, but so far, it seems to work :-)! I'll try to only use CLI-equivalents if I run into any more errors going forward. Thanks for your help!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜