A Generalized Parsing Class for MFC

One of the many tasks that a programmer has is taking a set of characters and breaking it down ino its discrete parts. This may be a comma delimited data file, a full directory path, or a set of program directives to perform an action verb and supply arguments. I often do this to implement a command handler for other classes. Rather than send the data to the class as disparate arguments I build a command string such as "Title=the Title@Start Date=12/12/1998@price=12.45" and pass it to the class which then parses the command string and sets the appropriate class variables. The advantage is that I don't have a particular order to send the data, one function can handle all the data inout for a class, and I can add more data members or action verbs without altering the public interface to the class at all, even by addition.

The class is very simple to use. All that you need to provide is a data string to be parsed and a set of delimiters that seperate the various fields. In the above case that would be:

parser.Parse("Titlle=the Title@Start Date=12/12/1998@price=12.45","=@");
There is also a class member that will read the data from a file and parse it.

The class is really brain dead to use. Below is a sample of the code used in the demo to parse user input strings:

void CMainView::OnBtnparse() 
{
	CParseIt	parser;						//	create a parser object
	CString		TheData;					// place to put field data into
	UpdateData();							//	Get it current
	if(!parser.Parse(m_Data,m_Seperator))   // this does all the work 
		return;								//	if here null string passed
	InitList();								//	empty current data from list ctrl
	for ( int y=0; y < parser.GetNumFields();++y) //  loop thru getting all the data
	{
		parser.GetField(y+1,TheData);
		AddItemToList(y+1,TheData);			//	add it to the list
	}
}
There are also functions to retrieve the data as strings, CStrings,longs (DWORD),doubles, and ints. The data is all stored as type char so it can be retrieved in any form it can be represented as. Notice above I get everything into a CString. This could just as easily be a double or int if the data could be described as that type of variable. Just pass GetField a reference to the type of data you wish returned and it does the conversion for you. Set Doc.rtf for details on these functions.

Download demo project - 25.6 KB

Download source - 6 KB



About the Author

Richard Stringer

C C++ ASM are my currrent languages of choice. Currently writing MFC apps for insurance companies