Format Specifiers CString::Format

Remarks

Call this member function to write formatted data to a CString in the same way that sprintf formats data into a C-style character array. This function formats and stores a series of characters and values in the CString. Each optional argument (if any) is converted and output according to the corresponding format specification in lpszFormat or from the string resource identified by nFormatID.

The call will fail if the string object itself is offered as a parameter to Format. For example, the following code:

CString str = "Some Data";
str.Format("%s%d", str, 123);   // Attention: str is also used in the parameter list.

will cause unpredictable results.

When you pass a character string as an optional argument, you must cast it explicitly as LPCTSTR. The format has the same form and function as the format argument for the printf function. (For a description of the format and arguments, see http://msdn.microsoft.com/en-us/library/ms396940(v=vs.60).aspx in the Run-Time Library Reference.) A null character is appended to the end of the characters written.

For more information, see http://msdn.microsoft.com/en-us/library/ms396977(v=vs.60).aspx in the Run-Time Library Reference.

Example

CString str;

str.Format(_T("Floating point: %.2f\n"), 12345.12345);
_tprintf("%s", (LPCTSTR) str);

str.Format(_T("Left-justified integer: %.6d\n"), 35);
_tprintf("%s", (LPCTSTR) str);

str.Format(IDS_SCORE, 5, 3);
_tprintf("%s", (LPCTSTR) str);

Output

If the application has a string resource with the identifier IDS_SCORE that contains the string “Penguins: %d\nFlyers  : %d\n”, the above code fragment produces this output:

Floating point: 12345.12
Left-justified integer: 000035
Penguins: 5
Flyers  : 3

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 }

 

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 %%
В жизни программиста часто возникают ситуации, когда необходимо преобразовать int в char и обратно. 
Здесь хотел бы Вам показать несколько полезных примеров, оторыми пользуюсь сам.

С/С++

Include: stdlib.h или math.h

Функции:

        double        atof( char *string );
        int           atoi( char *string );
        long          atol( char *string );
        long double   _atold( char *string );

Как видно данные функции преобразуют символьную строку в число. Пример:

#include <iostream.h>
#include <stdlib.h>

int main()
{
        char * szString = "0123456789";
        int i;
        i = atoi(szString);
        cout<<i;
        return 0;
}

Теперь наоборот, из число в символьную строку.

char *itoa( int value,  char *string, int radix );
char *ltoa( long value, char *string, int radix);
char *ultoa( unsigned long value, char*string, int radix );

 Пример:

#include <iostream.h>
#include <stdlib.h>

int main()
{
        char * szString = new char[17];
        int i = 1234567890;
        itoa(i,szString,10);
        cout<<szString;
        delete szString;
        return 0;
}

API
В Api функциях нашел только преобразование из числа в символьную строку:

int wsprintf(LPTSTR lpOut, LPCTSTR lpFmt, ...);

Пример:

#include <iostream.h>
#include <windows.h>

int main()
{
        char * szString = new char[17];
        int i = 12345;
        wsprintf(szString,"%d",i);
        cout<<szString;
        delete szString;
        return 0;
}

MFC
В MFC есть очень удобный класс по работе со строками CString, в его составе есть метод Format().

Пример:

#include <iostream.h>
#include <afx.h>

int main()
{
        CString m_string;
        int i = 123456789;
        m_string.Format("%d",i);
        cout<<m_string;
        return 0;
}

Здесь описаны не все способы, надеюсь, что-то Вам пригодится.

http://msdn.microsoft.com/en-us/library/aa314327%28v=vs.60%29.aspx

http://www.cyberguru.ru/cpp-sources/algorithms/preobrazovanie-chisel-v-stroku-i-obratno.html