The Format function in MFC

Source: Internet
Author: User
Tags integer numbers string format truncated

In MFC programs, using CString to process strings is a good choice. CString can handle both Unicode-standard strings and ANSI-standard strings. The format method of CString gives us a lot of convenience in converting strings, such as common int, float, and double, which can be implemented with a single line of code to convert the numeric types to CString strings.

First look at format characters for the conversion:

%c single character

%d decimal integer (int)

%ld decimal integer (Long)

%f Decimal Floating point number (float)

%LF Decimal Floating point number (double)

%o Octal number

%s string

%u unsigned decimal number

%x hexadecimal number

1. Convert int to CString:

CString str;

int number=15;

Str. Format (_t ("%d"), number);//str= "15"

Str. Format (_t ("%4d"), number),//str= "15" (preceded by two spaces, 4 means 4 bits will be occupied, if the digits exceed 4 bits will output all numbers, will not be truncated)

Str. Format (_t ("%.4d"), number); //str= "0015" (. 4 means 4 bits will be consumed if the number exceeds 4 bits will output all digits and will not be truncated)

The method of converting a long to CString is similar to the above, just change%d to%ld .

2. Double conversion to CString:

CString str;

Double num=1.46;

Str. Format (_t ("%LF"), num);//str= "1.46"

Str. Format (_t ("%.1LF"), num),//str= "1.5" (. 1 for 1 digits after the decimal point, and rounding for more than 1 digits after the decimal point)

Str. Format (_t ("%.4f"), num);//str= "1.4600"

Str. Format (_t ("%7.4f"), num),//str= "1.4600" (preceded by 1 spaces)

The method of converting float to CString is similar to the above, and it is possible to change the lf% to f% .

3. Convert decimal number to octal:

CString str;

int num=255;

Str. Format (_t ("%o"), num);//str= "377"

Str. Format (_t ("%.8o"), num); Str= "00000377"

Format is a very common, but it seems very annoying method, the following is its complete overview, for everyone to query:

The formatted string format ("%d", 12) means that a formatted character is to be shaped (I think it is to keep its shape unchanged)
1). The format description always starts with a% character, and the following is a description of the format of different types of data after the% number:
D Output signed decimal number
o Output unsigned octal number
x output unsigned hexadecimal number
U Output unsigned number
C Output Single character
s output a string of characters
F Output Real number (6 decimal places)
E output real numbers in exponential form
G Choose the format of the output width in F and e format, do not output 0
LD input-Output Long data
LF input/output double type data
m data output width m
. n Output decimal digits N


One, the string

First look at its statement:
function Format (const format:string; const Args:array of const): string; overload;
In fact, the Format method has two forms, the other is three parameters, the main difference is that it is thread-safe,
But not much, so here's only the first introduction:

function Format (const format:string; const Args:array of const): string; overload;
The format parameter is a formatted string that is used to format the value inside args. What is args?
It is a Variant array, that is, it can have multiple parameters, and each parameter can be different.
As in the following example:
Format ("My name is%6s", "Wind");
After returning is
My name is wind

Now look at the details of the format parameter:
Normal strings can be written in format, such as "My Name is"
However, some format instruction characters have special meanings, such as "%6s"

Format directives have the following form:
"%" [index ":"] ["-"] [width] ["." Prec] Type
It starts with "%" and ends with type, and type represents a specific type. The middle is used to
The format type of the instruction character, which is optional.

First look at Type,type can be the following characters:
d 10 number, representing an integer value
You and d are integer values, but it is unsigned, and if the corresponding value is negative, it is returned
is a 2 of the 32 times minus this absolute number
such as: Format ("This is%u",-2);
Returned: This is 4294967294
f corresponding floating-point number
e scientific notation, corresponding to integers and floating-point numbers,
such as format ("This is%e",-2.22);
Returned by: this is-2.220000e+000
Wait a minute. If you reduce the precision of the number
G This can only correspond to floating-point type, and it will remove the extra number in the value
such as format ("This is%g", 02.200);
Returned: This is 2.2
n can only correspond to floating point type, the value is converted into the form of a number. Look at an example and you'll see.
Format ("This is%n", 4552.2176);
Returns the IS 4,552.22
Note that there are two points, one is only indicated to the two digits after the decimal, and so on, say how to eliminate this situation
Second, even if the decimal is not truncated, it will not be separated by commas like the integer part.
M coin type, but there is a better format method for currency types, here is simply formatting
In addition it corresponds only to floating-point values
Format ("This is%m", 9552.21);
return: This is¥9,552.21
P corresponds to the pointer type, and the returned value is the address of the pointer, expressed in 16-binary form
For example:
Format ("This is%p", p);
The contents of Edit1 are: this is 0012f548
s corresponds to a string type, no more talking.
x must be an integer value, returned in 16-binary form
Format ("This is%x", 15);
Return yes: this is F

Type is complete, instructions for formatting the type are described below:
[index]: How to express this, see an example
Format ("This is%d%d", 12,13);
Where the first%d index is 0, the second%d is 1, so the character is displayed
Yes 12 13

And if you define this:
Format ("This is%1:d%0:d", 12,13);
Then the returned string becomes the
This is 13 12
Now do you understand that index in [index:] indicates that the parameter in args is displayed in the
Order

There is also the case if such format ("%d%d%0:d%d", 1, 2, 3, 4);
will return 1 2 3 1 2.
If you want to return 1 2 3 1 4, this must be the case:
Format ("%d%d%d%0:d%3:d", 1, 2, 3, 4);
However, it is important to note that the index cannot exceed the number of args, or it will cause an exception
such as format ("This is%2:d%0:d", 12,13); Error
Since there are only 12 132 numbers in args, index can only be 0 or 1, and here 2 is wrong.
[Width] Specifies the width of the value to be formatted, see an example to see
Format ("This is%4d", 12);
Output yes: This is 12
This is easier, but if the value of width is less than the length of the parameter, there is no effect.
such as: Format ("This is%1d", 12);
Output yes: This is 12
["-"] This specified parameter is left-aligned, and [width] together to see the effect:
Format ("This is%-4d,yes", 12);
Outputs are: This is a and yes

["." Prec] Specifies the precision, which works best for floating point numbers:
Format (' This is%.2f ', [' 1.1234]);
Output this is 1.12
Format (' This is%.7f ', [' 1.1234]);
Lost This is 1.1234000
For integer numbers, if the number of bits of the prec, such as the Integer, is small, there is no effect
Conversely, larger than the number of digits of the shaping value, the value of the integer will be preceded by 0
Format (' This is%.7d ', [1234]);
Output: This is 0001234]
For a character type, just as opposed to an integer value, if the PREC is larger than the length of the string type
is not effective, and vice versa is less than the length of the string type, it truncates the trailing character
Format (' This is%.2s ', [' 1234 ']);
Output Yes 12
And the example above says:
Format (' This is%e ', [-2.22]);
Returned by: this is-2.22000000000000e+000
How to get rid of the extra 0, that's it.
Format (' This is%.2e ', [-2.22]);

Well, the first one is finally finished, so you should be familiar with his application.

M_result. Format ("The city you selected is:/r/n%s,/r/n your chosen person is:/r/n%s", city1 + city2 + city3,people);
UpdateData (0);

Format Summary:
(1) The most commonly used format is%d, meaning that an integer is printed in 10 binary form.
If the output integer is a negative number, the first character of the output is the '-'
(2) The%u format is similar to the%d format, except that it requires the printing of unsigned 10 binary integers.
(3)%o format request output 8 binary integer
(4)%x and%x format request Output 16 integer.
The%x format uses lowercase letters a,b,c,d,e,f to represent numbers between 10 and 15.
The a,b,c,d,e,f in the%x format to represent numbers between 10 and 15.
Common denominator: 8 binary and 16 binary integers are always processed as unsigned numbers.
(5) The%s format is used to print a string, and the corresponding parameter should be a character pointer, and the character to be output starts at the address pointed to by the pointer until a null character ('/0 ') appears
Before it terminates.
(6) The%c format is used to print a single character: for example:
printf ("%c", c); equivalent to Putchar©;
(7)%g,%f and%e These three formats are used to print floating-point values.
The%g format is especially useful for printing floating-point numbers that do not need to be aligned by column. It has two functions:
One, remove the extra 0 (not up to six digits) of the tail
Second, retain six digits (extra six bits)
The%e format is used to display the exponential form when printing floating-point numbers: For example: Output pi: 3.141593e+00
The difference between the two:
The number printed in%g format is a total of 6 valid digits
%e format to print out 6 digits after the decimal point
%f prohibit the use of exponential form to represent floating-point numbers. So the PI output is: 3.141593
(but note its accuracy requirement: Also 6 digits after the decimal point)
(8) The percent format is used to print a% character.
(9)%e and%g only use capital letters (e) in place of lowercase letters (e) when outputting
There are also some points of knowledge to note:

***************************************
Alignment rules:
(1) When the specified width is greater than the number of bits to output, the number is right aligned and the left side is blank
The current prefix '-', want to count left-justified, right-side fill space
A big premise: the prefix '-' is only meaningful if the "specified width" exists.
Experience: In general, the left-aligned form looks neat and tidy.
***************************************
Tips for outputting a sign: (remember) for example:
printf ("%+d%+d%+d/n", -5,0,5);
Just add a "+" number in the middle of the line. The function is to output the symbol bit (that is, the number of the sign)
If you do not want the ' + ' sign in front of a positive number, use the following method

***************************************
Just add a "" number (that is, a space) in the middle of the line. (remember) For example:
Function: If a number is non-negative, insert a space in front of it.
int i;
for (i=-3;i<=3;i++)
printf ("% d/n", i); Note that there is a space between% and D
The output results are as follows:
-3
-2
-1
0
1
2
3
Question: If ' + ' and ' are present in the middle ', then ' + ' shall prevail.
Two symbols in common: the number used to align the output: (especially for decimals)
Two formats:%+e and% E
The basic input and output functions in the C language are:
Putchar (): Outputs a character constant in a variable to the display screen;
GetChar (); Enter a character constant from the keyboard, which is the value of the function;
printf (); The various data in the keyboard are formatted and output to the monitor screen;
scanf (); Enter various types of data from the keyboard and store them in the program variables;
Puts (): Outputs a string constant in the array variable to the display screen;
Get (): Enter a string constant from the keyboard and place it in an array of programs.
SSCANF (); Extracts various types of data from a string.
Putchar () and GetChar () as implies is to get a character from the input stream and output a character, which is relatively simple and does not speak more.
Examples are as follows:
char C = GetChar ();
Putchar©;
formatting input and Output scanf () and printf () are the most useful, so focus on them.
printf ():
General form:
printf ("Format control". Output list);
eg:printf ("a=%d,b=%f,c=%c/n", a,b,c);
1; Format control.
Format control is a string enclosed in double quotation marks, also known as a "conversion control string," which contains the following two pieces of information.
Format Description: Composed of "%" and format characters, such as%d,%f,%c, his role is to convert the output data to the specified format output, the format of the description is always started by the "%" character.

Ordinary characters: characters that need to be output as-is, or characters with special meanings, such as/n,/t.
2. Output list
is some data that needs to be output, or it can be an expression, separated by commas if you need to output multiple variables or expressions in a function.
Output of some special characters:
The output of single quotation marks, double quotes, and backslashes is preceded by the escape character "/"
such as: "/" ","/"", "//"
The output of% is connected with two percent of the total, i.e. printf ("%");

The usual format descriptions are as follows:
Format characters
D output signed integers in decimal form (positive numbers do not output symbols)
o Output unsigned integers in eight binary form (do not output prefix O)
x output unsigned integers in 16-binary form (not output prefix ox)
U output unsigned integers in decimal form
F Output single-precision real numbers in decimal form
LF output double-precision real numbers in decimal form
E output single, double-precision real numbers in exponential form
G output single, double-precision real numbers with shorter output widths in the%f%e
C Output Single character
S output string
Here to emphasize: many articles on the internet said F and LF is the same, that no matter the single-precision, double-precision floating point number, can be used F, but I did the test on the POJ, the output double with f can do, but read in, with F on the report WA, so everyone if the double read and write, use LF bar.
Speaking of double, and then a long-winded, we recommend that you use the floating point when you use double, do not use float, because in many cases, float precision is not enough will lead to WA.
Special:
For the input and output of 64-bit integers, the 64-bit integers are in the C + + environment on POJ (that is, VC):
__int64 (note int preceded by two underscores)
The input and output format is "%i64d".
In a g++ environment (that is, the dev C + +) 64-bit integer is
Long Long
The input and output format is "%lld".

Output width
A decimal integer that represents the minimum number of digits for the output. Note that if the actual number of digits is greater than the defined width, the actual number of digits is output, and if the actual number of digits is less than the defined width, a space or 0 is provided.
Precision
Precision format characters with "." Begins with a decimal integer followed by. The meaning is: if the output number, then the number of decimal places, if the output is a character, the number of output characters, if the actual number of digits is greater than the defined number of precision, the section is truncated.
Flag Format Characters
-Results left-aligned, right-hand blanks
+ Output symbol (plus or minus) the space output value is a positive-time space, minus the negative.
For example:
Double c=24212345.24232;
printf ("%020.4"); Indicates that the output is accurate to 4 digits after the decimal point, the output is 20 bits, if there is a spare bit 0.
scanf
Many usages of scanf are corresponding to printf, so they are not to be mentioned.
Say scanf a particularly useful place, is to filter out some unwanted things.
Examples are as follows:
For example, the input is a date yyyy-mm-dd, it can be written like this:
int year,moth,day;
scanf ("%d-%d-%d", &year,&moth,&day);
Another example:
scanf ("%3d%*3d%2d", &m,&n); Input 113 118 69 Return Vehicle (the system assigns 113 to M, 69 to N, because the * number means skipping its corresponding data so 118 does not give any variables)
Puts () used not much, and basically can be replaced with printf (), so no longer say more.
Get () is a string that gets a line from the input stream into the character array:
Char in[100];
Gets (in);
Perhaps the most error-prone place is the string input, so emphasize:
Characters that can be entered in the string are:
GetChar (), scanf ("%c"); scanf ("%s"), gets ()
Where the functions of GetChar () and scanf ("%c") are the same.
It is important to note that these two functions read the characters in the current position in the input stream.
Like what:
scanf ("%d", &n);
c = GetChar ();
Assuming input 67/(assuming "/" for carriage return), the first scanf reads into an integer 67, after the current input stream position is 67, that is, to the carriage return character, so the second getchar () reads a carriage return, that is, C = '/n '.
Similarly, gets () reads a line of strings from the current location.
Like what:
scanf ("%d", &n);
Gets (str);
The string that is read into the character array is "/n" now.
So usually after reading into a non-string type with scanf, if you want to read the character, or the character array, use an extra GetChar () to read the carriage return, if there is more than a carriage return, there may be extra space, you can read it with Get ().
Unlike the above, scanf ("%s") will ignore whitespace, carriage returns, and tab characters when it is read in. And with spaces, carriage returns, and tabs as a sign of the end of the string.
Often have such a problem, enter the first line is an integer, then the first of each line is a character, used to indicate some kind of operation, followed by some data, such as:
4
A 100 2
B 23
A 23 89
B 34
Like this type of input, you need to be careful not to read the characters into a carriage return.
In order to prevent accidents, I generally deal with this type of input:
Char model[2];
SCANF ("%d", &n);
For (...,...,...) {
scanf ("%s", model);
if (model[0] = = ' A ') {
}
else{
}
}
SSCANF ():
SSCANF () is often used to break down strings, the function is very powerful, but a lot of functions require regular expression of knowledge, so introduce the simplest of several usages, if you want to know more words, go online to find it.
1.
Char str[100],str1[100],str2[100];
Gets (str);
SSCANF (str, "%s%s", STR1,STR2);
Divides the read-in string into two strings by a space, a tab, or a carriage return character.
2
Takes a string of the specified length. As in the following example, take a string with a maximum length of 4 bytes.
SSCANF ("123456", "%4s", str);

The Format function in MFC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.