Formatting an Edit Box Using strstream

Objective:  you have a floating point variable, and you want to apply iostream-type formatting to it so that it looks good in an Edit box.  So instead of using iostream objects (like cout), we'll use strstream (string stream) objects that use a regular character array to hold the formatted character that ultimately need to be displayed.

What This Looks Like When You Run It

Key concepts -

You need to include

You need to define a character array that will hold the 'output' string. You need to define the string stream object, and initialize it so that it is associated with the character array -- My sample uses UpdateData to get a floating point number from the GUI, then applies ordinary iostream-type filters to convert the number so that it has 2 digits of accuracy. You then have to convert the character array to floating point, assuming that the member variable (m-textbox) associated with the Edit box was a floating point variable. Finally, we use UpdateData to refresh the Edit box.



Click HERE to download a zip containing all the files in the project

Filenames used in the project --

format.aps format.clw format.cpp format.dsp format.dsw format.h
format.ncb format.opt format.plg format.rc FormatDlg.cpp FormatDlg.h readme.txt
res directory --
resource.h stdafx.cpp stdafx.h


Code needed at the top of the Dialog --
#include <strstrea.h>
#include <iomanip.h>
Code needed to go with the 'Format' button --
void CFormatDlg::OnOK()
{
 float x;

 static char chararray[10];
 static ostrstream stringStream(chararray, 10);

 UpdateData(TRUE);
 x = m_textbox;

 stringStream  << setiosflags(ios::fixed)  << setprecision(2)               <<setiosflags(ios::showpoint) <<  x << ends;

 m_textbox = atof(chararray);

 UpdateData(FALSE);
 stringStream.seekp(0);  //resets the stream for susequent uses
 //MessageBox(chararray);
      //uncomment this, and then input 1.9978 and see what happens

}


No, you can't redo lab 3 !!
Created & Maintained by DrB on Mon, Oct 23, 2000