Format function and Format input and output in CString

Source: Internet
Author: User
Tags truncated

Format function and Format input and output in CString
Format function and Format input and output in CString

Format is a very common but annoying method. The following is a complete overview of it for your query:

Formatting string forma (% d, 12) means to format an integer character (I think it is to keep its shape unchanged)
1). The format description always starts with % characters. The following describes the formats of different types of data after % signs:
D. The output is in decimal notation.
O output unsigned Octal numbers
X output unsigned hexadecimal number
Unsigned number of u output
C Outputs a single character
S outputs a string of characters
F output real number (6 decimal places)
E. Output real numbers in exponential form
G: select the format with a small output width in the f and E format, and do not output 0
Ld Input and Output long data
Lf Input and Output double type data
M data output width is m
. N number of output decimal places is n


I. String

First, let's look at its statement:
Function Format (const Format: string; const Args: array of const): string; overload;
In fact, the Format method has two forms, and the other is three parameters. The main difference is that it is thread-safe,
But it is not widely used, so here we will only introduce the first one:

Function Format (const Format: string; const Args: array of const): string; overload;
The Format parameter is a Format string used to Format the values in Args. What is Args,
It is a variant array, that is, it can have multiple parameters, and each parameter can be different.
For example:
Format (my name is % 6 s, wind );
The returned result is
My name is wind

Now let's take a look at the details of the Format parameter:
The Format can be a common string, for example, my name is
However, some command characters in the format have special meanings, such as % 6 s.

The format command has the following forms:
% [Index:] [-] [width] [. prec] type
It starts with % and ends with type. type indicates a specific type. Is Used in the middle
It is optional to format type instruction characters.

Let's take a look at type. type can contain the following characters:
D in decimal format, indicating an integer value
U is an integer value like d, but it is unsigned. If its value is negative
Is the number of the 32 power minus the absolute value of 2.
For example, Format (this is % u,-2 );
The returned result is: this is 4294967294
F corresponds to a floating point number
E scientific notation, corresponding to integer and floating point number,
For example, Format (this is % e,-2.22 );
The returned result is: this is-2.220000E + 000.
It will be explained later if the precision of the number is reduced.
G can only correspond to the floating point type, and it will remove the excess number in the value
For example, Format (this is % g, 02.200 );
The returned result is: this is 2.2
N can only correspond to the floating point type, and the value is converted to the number form. Let's see an example.
Format (this is % n, 4552.2176 );
This is 4,552.22.
Note that there are two points. One is to indicate only the last two digits of the decimal number. Let's wait and explain how to eliminate this situation.
Second, even if the decimal number is not truncated, it will not be separated by commas like an integer.
M coin type, but there is a better way to format the currency type, here is just a simple format
In addition, it only corresponds to the floating point value.
Format (this is % m, 9552.21 );
Return Value: this is ¥9,552.21.
P corresponds to the pointer type. The returned value is the pointer address, expressed in hexadecimal format.
For example:
Format (this is % p, p );
The content of Edit1 is: this is 0012F548
S corresponds to the string type. Needless to say
X must be an integer value, which is returned in hexadecimal format.
Format (this is % X, 15 );
The returned result is: this is F.

After the Type description is completed, the following describes the instructions for formatting the Type:
[Index:] How to express this? Let's look at an example.
Format (this is % d, 12, 13 );
The index of the first % d is 0, and the second % d is 1.
Yes. this is 12 13.

If you define it as follows:
Format (this is % 1: d % 0: d, 12, 13 );
Then the returned string is changed
This is 13 12
Do you understand now? The index in [index:] indicates
Sequence

There is also a case where such Format (% d % 0: d % d, 1, 2, 3, 4 );
1 2 3 1 2 is returned.
If you want to return 1 2 3 1 4, you must set it as follows:
Format (% d % 0: d % 3: d, 1, 2, 3, 4 );
Note that the index cannot exceed the number in Args. Otherwise, an exception may occur.
For example, Format (this is % 2: d % 0: d, 12, 13); // error
Because Args has only 12 13 numbers, the Index can only be 0 or 1. If it is 2, it will be wrong.
[Width] specifies the width of the value to be formatted. You can see the following example:
Format (this is % 4d, 12 );
Output: this is 12
This is relatively easy, but if the Width value is smaller than the length of the parameter, there is no effect.
For example, Format (this is % 1d, 12 );
Output: this is 12
[-] This specified parameter is aligned to the left, and is combined with [width] to see the effect:
Format (this is %-4d, yes, 12 );
Output: this is 12, yes

[. Prec] specifies the precision, which has the best effect on floating point numbers:
Format ('this is %. 2f ', ['1. 1234]);
Output this is 1.12
Format ('this is %. 7f', ['1. 1234]);
This is 1.1234000

For integer data, if the prec such as integer data has a small number of digits, there is no effect.
Otherwise, it is greater than the number of digits of the integer value.
Format ('this is %. 7d ', [1234]);
Output: this is 0001234]

For the character type, it is just opposite to the integer value. If the prec type is longer than the string type
It does not work. If the string type is smaller than the string type, the trailing characters are truncated.
Format ('this is %. 2s ', ['123']);
The output is this is 12.

The example above is as follows:
Format ('this is % E', [-2.22]);
The returned result is: this is-2.22000000000000E + 000.
How can we remove the excess 0?
Format ('this is %. 2e', [-2.22]);

Okay. The first one is finished. I should be familiar with his application.

M_result.Format (the city you selected is: % s, the person you selected is: % s, city1 + city2 + city3, people );
UpdateData (0 );

Summary:
(1) The most common format is % d. The meaning is to print an integer in the decimal format.
If the output integer is negative, the first character of the output is '-'.
(2) The format of % u is similar to that of % d, except that an unsigned 10-digit integer is printed.
(3) % o format request output 8-digit integer
(4) Request output hexadecimal integers in % x and % X formats.
In % x format, lowercase letters a, B, c, d, e, f are used to represent the numbers between 10 and 15.
In % X format, uppercase letters A, B, C, D, E, F are used to represent the numbers between 10 and 15.
In common: octal and hexadecimal integers are always processed as unsigned numbers.
(5) The % s format is used to print a string. The corresponding parameter should be a character pointer. The character to be output starts from the address pointed to by the pointer, until an empty character ('') appears ('')
.
(6) % c format is used to print a single character: for example:
Printf (% c, c); equivalent to putchar©;
(7) % g, % f, and % e are used to print floating point values.
The % g format is especially useful for printing floating-point numbers that do not require column-aligned. It has two functions:
1. Remove the excess zero at the end of the number (the number does not reach six digits)
2. Retain the six valid digits (the remaining six digits)
When the % eformat is used to print floating point numbers, it is displayed in the exponential form. For example, when the circumference rate is output, it is 3.141593e + 00.
Differences between the two:
The number printed in % g format is a total of 6 Valid digits.
% Eformat: print the 6-digit valid number after the decimal point
% F do not use an exponential representation of floating point numbers. Therefore, the circumference rate is 3.141593.
(But pay attention to its precision requirement: it is also a 6-digit valid number after the decimal point)
(8) % is used to print a % character.
(9) % E and % G only replace lowercase letters (E) with uppercase letters (e) in the output)
Note the following knowledge points:

***************************************
Alignment rules:
(1) When the specified width is greater than the number of digits to be output, the number is right aligned and spaces are filled on the left.
When the prefix '-' is used, the numbers must be left aligned and spaces must be filled on the right.
Big premise: the prefix '-' is meaningful only when "specified width" exists.
Experience: In general, the left-side alignment looks neat and tidy.
***************************************
Tips for outputting positive and negative numbers: (remember) for example:
Printf (% + d,-5, 0, 5 );
You only need to add a "+" in the middle. The role is to output the sign bit (that is, the plus or minus sign of the number)
If you do not want the '+' sign to appear before a positive number, use the following method:

***************************************
You only need to add a space in the middle. (Remember) for example:
Function: If a number is non-negative, a space is inserted before it.
Int I;
For (I =-3; I <= 3; I ++)
Printf (% d, I); // note that there is a space between % and d.
The output result is as follows:
-3
-2
-1
0
1
2
3
Problem: If '+' and 'appear in the "Middle" at the same time,' + 'should prevail.
The two symbols share the same thing: (especially for decimal places)
Two formats: % + e and % e
Basic Input and Output Functions in C language include:
Putchar (): Output A character constant in the variable to the display screen;
Getchar (); input a character constant from the keyboard. This constant is the value of this function;
Printf (); format and control all types of data on the keyboard to output to the display screen;
Scanf (); input various types of data from the keyboard and store the data in program variables;
Puts (): outputs a String constant in the array variable to the display screen;
Gets (): enter a String constant on the keyboard and place it in the array of the program.
Sscanf (); extracts various types of data from a string.
Putchar () and getchar () names are used to get a character from the input stream and output a character, which is relatively simple and will not be discussed more.
Example:
Char c = getchar ();
Putchar©;
Formatting the input and output scanf () and printf () are the most useful.
Printf ():
General format:
Printf (format control. Output list );
Eg: printf (a = % d, B = % f, c = % c, a, B, c );
1; format control.
Format control is a string enclosed in double quotes, also known as a conversion control string. It contains the following two parts.
Format description: it consists of % and format characters, such as % d, % f, and % c. It is used to convert the output data to the specified format, the format description always starts with % characters.

Common Character: a character that needs to be output as is, or a character with special meanings, such ,.
2. Output list
The data to be output can also be an expression. If multiple variables or expressions need to be output in a function, separate them with commas.
Output of some special characters:
Single quotation marks, double quotation marks, and backslash output are preceded by escape characters ""
For example, "'", "", "\"
% Of the output uses two % together, that is, printf ("% ");

Common formats are described as follows:
Format characters
D. Output signed integers in decimal form (positive numbers do not output symbols)
O outputs unsigned integers in octal form (no prefix O is output)
X outputs an unsigned integer in hexadecimal format (the OX prefix is not output)
U outputs an unsigned integer in decimal format
F outputs Single-precision real numbers in decimal form
Lf outputs double-precision real numbers in decimal form
E outputs Single and Double Precision Real Numbers in exponential form
G outputs Single and Double precision real numbers with a shorter output width in % f % e
C Outputs a single character
S output string
I would like to emphasize that f is the same as lf in many online articles, that is, f can be used regardless of Single-precision or double-precision floating-point numbers, but I have tested it on POJ, it is true that f can be used to output Double data. However, if f is used for reading and writing Double data, lf is used.
Speaking of Double, we recommend that you use Double instead of float when using floating point numbers, because in many cases, the float precision is insufficient, leading to WA.
Special:
For 64-bit integer input and output, the 64-bit integer is:
_ Int64 (note that the front of int Is two underscores)
The input/output format is "% I64d ".
In the G ++ environment (Dev C ++), the 64-bit integer is
Long
The input and output formats are "% lld ".

Output width
The minimum number of digits of the output is expressed by a decimal integer. Note: If the actual number of digits is greater than the defined width, the actual number of digits is output. If the actual number of digits is less than the defined width, spaces or 0 are supplemented.
Precision
The precision format character starts with "." and is followed by a decimal integer. It indicates the number of digits to be output. If the number is output, it indicates the number of digits to be output. If the actual number of digits is greater than the defined precision, the part that exceeds the limit is truncated.
Character in logo format
-The result is left aligned with a space on the right.
+ Space of the output symbol (positive or negative). The output value is a positive value with a space and a negative value with a negative value.
For example:
Double c = 24212345.24232;
Printf ("% 020.4"); indicates that the output is accurate to the fourth digit after the decimal point, and the output occupies 20 digits.
Scanf:
Many scanf usage methods correspond to printf, so we will not repeat them here.
Scanf is particularly useful for filtering out unwanted things.
Example:
For example, if the input date is yyyy-mm-dd, you can write it as follows:
Int year, moth, day;
Scanf ("% d-% d", & year, & moth, & day );
For example:
Scanf (% 3d % * 3d % 2d, & m, & n); enter 113 118 69 and press enter (the system will assign 113 to m and 69 to n, because "*" indicates that the corresponding data is skipped, "118" does not assign any variable)
Puts () is rarely used and can be replaced by printf.
Gets () is to get a string from the input stream and put it into the character array:
Char in [100];
Gets (in );
The most common error is the string input:
Can carry on the character, string inputs include:
Getchar (), scanf ("% c"); scanf ("% s"), gets ()
Getchar () and scanf ("% c") have the same functions.
Note that the two functions read the characters at the current position in the input stream,
For example:
Scanf ("% d", & n );
C = getchar ();
Assume that the input 67/(assuming "/" represents the carriage return), the first scanf reads an integer 67, and the current input stream is after 67, that is, pointing to the carriage return, therefore, the second getchar () reads a carriage return, that is, c = ''.
Similarly, gets () also reads a line of strings from the current position.
For example:
Scanf ("% d", & n );
Gets (str );
The character string in the character array is "".
Therefore, after reading a non-string type with scanf, if you want to read characters or character arrays, use an additional getchar () to read the carriage return, if there is more than one carriage return followed by any extra space, use gets () to read it.
Different from the preceding, scanf ("% s") ignores spaces, carriage returns, and tabs. And uses spaces, carriage returns, and tabs as the character string ending signs.
This is often the case where the first line of input is an integer, and the first line of each line is a character to indicate an operation, followed by some data, such:
4
A 100 2
B 23
A 23 89
B 34
You need to be careful with such input. Do not read the character as a carriage return.
To prevent exceptions, I usually handle such input as follows:
Char model [2];
Scanf ("% d", & n );
For (...,...,...) {
Scanf ("% s", model );
If (model [0] = 'A '){
}
Else {
}
}
Sscanf ():
Sscanf () is often used to break down strings. It has very powerful functions, but many functions require the knowledge of regular expressions. So let's introduce the simplest usage. If you want to know more, find it online by yourself.
1.
Char str [2, 100], str1 [100], str2 [100];
Gets (str );
Sscanf (str, "% s", str1, str2 );
Splits the entire line of string into two strings by space, tab, or carriage return.
2
Returns the string of the specified length. In the following example, a string with a maximum length of 4 bytes is obtained.
Sscanf (123456, % 4 s, str );

 

Related Article

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.