Cstring: Format () function and format input and output (17:49:34)
Tags: miscellaneous categories:ProgramDesign
Format is a very common but annoying method. The following is a complete overview of it for your query:
Formatting string format ("% 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 contain common strings, such as "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 the type. The type can be a string of the following characters:
A ten-digit number represents an integer value.
U is an integer value like D, but it is unsigned, and if its corresponding value is negative, the return value
is a 32 power of 2 minus the number of the absolute value
such: format ("this is % u",-2);
the returned result is: This is 4294967294
F corresponds to a floating point number
E scientific notation, corresponding to the integer and floating point number.
for example, format ("this is % E",-2.22);
the returned result is: this is-2.220000e + 000
after a while, it means that if the precision of the number is reduced
G, it 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 into a number. I can see from an example that
Format ("this is % N", 4552.2176);
the returned result is this is 4,552.22
note that there are two points, first, it indicates only the last two digits of the decimal number. Wait and explain how to eliminate this situation.
second, even if the decimal number is not truncated, it also does not have a comma to separate the
M coin type, but there is a better way to format the currency type, here is just a simple format
and it only corresponds to the floating point value
Format ("this is % m", 9552.21);
return: this is ¥9,552.21
P corresponds to the pointer type. The returned value is the pointer address, expressed in hexadecimal format.
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 and return 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 );
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 \ r \ n % s, \ r \ n. The selected city is \ r \ n % s", city1 + city2 + city3, people );
Updatedata (0 );
Format Summary:
(1) the most common format is % d. The meaning is to print an integer in decimal format.
If the output integer is negative, the first character of the output is '-'.
(2) % u format is similar to % d format, only an unsigned 10-digit integer is required.
(3) % O format request output an octal integer
(4) % x and % x format request output a hexadecimal integer.
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 are used, b, C, D, E, F indicates the number between 10 and 15
commonalities: octal and hexadecimal integers are always processed as unsigned numbers.
(5) % 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, it is terminated only when an empty character ('\ 0')
appears.
(6) % C 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 particularly 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-digit valid number (the remaining six digits)
% egex is used to print floating point numbers. All values are displayed in the exponential form. For example, when the circumference rate is output: 3.141593e + 00
differences between the two:
the number printed in % G format is a total of 6 Valid digits
% E format: the number of 6 Valid digits after the decimal point is printed.
% f the exponential form is not allowed. to represent floating point numbers. Therefore, the circumference rate is output as follows: 3.141593
(but note its precision requirement: it is also a 6-digit valid number after the decimal point)
(8) % format is used to print a % character.
(9) % E and % G only replace the lower case letter (e) with the upper case letter (e) in the output.
note the following points:
************************************* **
alignment rules:
(1) when the specified width is greater than the number of digits to be output, the number is right aligned, and the left side is filled with spaces.
when the prefix is '-', the number is left aligned, right side fill space
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) example:
printf ("% + D % + d \ n",-5, 0, 5 );
you only need to add "+" in the middle. The function 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 the positive number, use the following method
************************************* **
you only need to add a "" sign in the middle (I .e: space. (Remember) for example:
function: If a number is not negative, insert a space before it.
int I;
for (I =-3; I <= 3; I ++)
printf ("% d \ n", 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,' + 'shall 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:
putchar (): outputs a character constant in the variable to the display screen;
getchar (); input a character constant from the keyboard, which is the value of the function;
printf (); Put all types of data on the keyboard, format control and output to the display screen;
scanf (); input various types of data from the keyboard and store the data in program variables;
puts (): output 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 (); extract various types of data from a string.
putchar () and getchar () are strings used to get a character from the input stream and output a character. They are relatively simple and will not be mentioned more.
example:
char c = getchar ();
putchar ?;
formatting input/output scanf () and printf () are the most useful methods.
printf ():
General Format:
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 "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 "%.
Common Character: a character that needs to be output as is, or a character with special meanings, such as \ n, \ t.
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 there are manyArticleBoth F and LF are the same, that is, F can be used regardless of single precision or Double Precision Floating Point Number. However, I did a test on poj and I can use F to output double values, however, when reading data, if F is used, then Wa is reported. So if you read and write data for double, 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 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 assign 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 = '\ n '.
Similarly, gets () also reads a line of strings from the current position.
For example:
Scanf ("% d", & N );
Gets (STR );
The string in the character array is \ n.
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 % 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 );