问题描述:

I'm trying to write some double values to a text file the user creates via a SaveFileDialog, but everytime I do a streamWriterVariable->Write(someDoubleVariable), I instead see some kind of weird ASCII character in the text file where the double should be (music note, |, copyright symbol, etc). I'm opening the file with notepad if it's that of any significance. A basic outline of my code:

SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog;

saveFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

saveFileDialog1->Title = "Save File Here";

saveFileDialog1->RestoreDirectory = true;

if (saveFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK )

{

FileInfo ^fleTest = gcnew FileInfo(saveFileDialog1->FileName);

StreamWriter ^sWriter = fleTest->CreateText();

sWriter->AutoFlush = true;

double test = 5.635; //Some arbitrary double I made up for test purposes

sWriter->Write(test);

sWriter->Flush();

sWriter->Close();

}


Thanks for your help!

网友答案:

Have you tried to set the encoding explicitly?

StreamWriter^ sWriter = gcnew StreamWriter(saveFileDialog1->FileName, false, System::Text::Encoding::ASCII);
网友答案:

The code you've provided does exactly what you ask it to, that is to write a double to the file in the internal computer format. What you most likely want it to write out the textual representation of the double.

In other words you should try sWriter->Write(test.ToString()) or some variation over this, to get the textual version of your double. This also applies to bool and most other variable representation.

相关阅读:
Top