How to format string

7 10 2012

Formatting a string is one of the most commonly used methods in our daily programming. But inappropriate usage of format specifiers may lead to unexpected crash. This post summarizes the format specifiers supported by CString Format method.

MFC class CString provides a Format method to format the string. String replaceable parameters (%s, %d, %c etc) can be used to format the string.

void Format(LPCTSTR lpszFormat, … );
LPCTSTR lpszFormat – format specifier

Format Specifiers

Sr.No. Specifier Description
1 String %s
2 Character %c
3 Integer %d or %i
4 Unsigned Integer %u
5 Float and double %f
6 ULONGLONG %I64u
7 SIZE_T and DWORD %lu
8 Format float with 3 decimal places %.3f
9 Format float with 3 decimal places, right justified with 5 characters %5.3f
10 Format float with 3 decimal places, left justified with 5 characters %-5.3f
11 Format int, left justified 5 characters %-5d
12 Format int, right justified 5 characters, use 0 to fill the field %05d
13 void pointer %p
14 Output a % sign %%

void FormatString()
{
	CString str;
	str.Format(_T("%s"), _T("Hello world!")); //Hello world!
	str.Format(_T("Integer - %d"), 123); //Integer - 123
	char temp1 = 'a';
	str.Format(_T("Character - %c"), temp1); //Character - a
	float temp2 = 1.234;
	str.Format(_T("Folat - %f"), temp2); //Folat - 1.234
	ULONGLONG temp3 = 123456789;
	str.Format(_T("ULONGLONG - %I64u"), temp3); //ULONGLONG - 123456789
	SIZE_T temp4 = 12344;
	str.Format(_T("SIZE_T - %lu"), temp4);//SIZE_T - 12344
	float temp5 = 1.234567;
	str.Format(_T("Float 3 decimal places - %.3f"), temp5);//Float 3 decimal places - 1.235
	str.Format(_T("Float 3 decimal places, right justified 5 chars - %5.3f"), temp5);//Float 3 decimal places, right justified 5 chars - 00001.234
	str.Format(_T("Float 3 decimal places, left justified 5 chars - %-5.3f"), temp5);//Float 3 decimal places, left justified 5 chars - 1.235
	int temp6 = 12;
	str.Format(_T("Int Left aligned 5 character - %.5d"), temp6);//Int Left aligned 5 character - 00012
	str.Format(_T("Int Right aligned 5 character, fill 0 - %05d"), temp6);//Int Right aligned 5 character, fill 0 - 00123
}

It is better to avoid string object itself as the parameter to Format method.

Advertisements

Actions

Information

One response

29 10 2013
vaishnavi

Thank you me being a beginner in mfc understood format() function well from this site.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: