Nate
Nate

Reputation: 65

StreamWriter trouble writing doubles to .txt file (C++)

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!

Upvotes: 0

Views: 736

Answers (2)

holroy
holroy

Reputation: 3127

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.

Upvotes: 0

Pragmateek
Pragmateek

Reputation: 13354

Have you tried to set the encoding explicitly?

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

Upvotes: 0

Related Questions