0

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!

Nate
  • 65
  • 1
  • 7

2 Answers2

0

Have you tried to set the encoding explicitly?

StreamWriter^ sWriter = gcnew StreamWriter(saveFileDialog1->FileName, false, System::Text::Encoding::ASCII);
Pragmateek
  • 13,174
  • 9
  • 74
  • 108
  • So enconding explicitly hasn't fully solved the problem but it's offered a kind of solution: when I encode explicitly and write only do writeLine(double), it works. If I do write(double) followed by any write("string") it messes up, in addition to any write(string) followed by a write(double). Needless to say though your advice has led me to a solution so thank you! For future reference I had two errors when trying your declaration: one, it claimed that ANSI wasn't an encoder type, and two, it said that it didn't expect a bool value for the 2nd spot in the parameter. Thanks though! – Nate Jun 07 '13 at 13:51
  • Oops I meant System::Text::Encoding::ASCII. Have you tried to open the resulting file with an advanced text editor like Notepad++? Moreover is the file always created from scratch, ie deleted before any new writes? – Pragmateek Jun 07 '13 at 14:34
0

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.

holroy
  • 3,047
  • 25
  • 41