Formatted input/output (c language super detailed series) (1)

Foreword;

Hello, everyone, my name is sy. Today we will mainly discuss formatted input/output (1), including the basic usage and precautions of printf and scanf, a simple understanding of conversion instructions, and an explanation of escape sequences. We will follow up Continue to bring in-depth study of conversion instructions and the knowledge of input buffering concepts related to files, including character input and output, line input and output, and block input and output. The knowledge we discuss today will be the content that is widely covered when getting started with the C language, as well as a summary of the pitfalls we often step on. Let’s take a look together~~

1. printf function

 Basic format: printf ( format string, expression 1, expression 2,... ); The printf function is used to display the contents of the format string and insert a possible value at the specified position in the string. A format string must be provided when calling printf .The parameter after the format string is the value inserted into the string when displayed (can be a constant, variable, and complex expression).

Format string: Contains ordinary characters and conversion instructions, where the conversion instructions begin with %  . The conversion specification is a placeholder used to represent the value to be filled during the printing processThe information following the % specifies the conversion of the value from the calculation and internal form (binary) to the form you want to print.

For example: Conversion description %d specifies that the printf function converts an int value from binary form to decimal form.

* The following points need to be noted:

1. The ordinary characters in the format string must be completely "copied" and displayed, and the conversion instructions must be "replaced" with displayed values . For example:

    int i, j;
	float x, y;
	i = 1;
	j = 2;
	x = 2.55f;
	y = 20.0f;
	printf("i=%d,j=%d\nx=%f,y=%f",i,j,x,y);

Output results: It can be seen that the ordinary characters "i=, j=, x=, y=" and "comma" in the format string are "copied" to the output line, while the values ​​of variables i, j, x, y are Replaced 4 conversion instructions in sequence.

 

2. Pay attention to whether the conversion description in the format string matches the number of output items.

· When there are more conversion instructions than the number of values ​​to be displayed:

    int i = 1;
	int j = 2;
	printf("%d %d\n", i);

Output result: It can be seen that the printf function will correctly display the value of i, and then display a meaningless value.

 

· When the number of conversion instructions is less than the number of values ​​to be displayed:

    int i = 1;
	int j = 2;
	printf("%d\n", i, j);

Output results: It can be seen that only the value of i is output, and the value of j is not displayed.

 

· Also pay attention to using the correct conversion specification to match the display item:

    int i = 1;
	float j = 2.5f;
	printf("%d %f", j, i);

Output results: It can be seen that if the order of int type variable i and float type variable j is placed in the wrong order, the program will produce meaningless output. 

 

2. Conversion instructions

* Conversion instructions provide programmers with a large number of methods to control the output format. Conversion instructions sometimes include formatting information, for example: use %.1f to display a float value with one digit after the decimal point.

* Generally, the conversion instructions can be in %m.pX format or -%m.pX format , where m and p are both integer constants, and X is a letter. m and p are user-defined according to needs. If p is omitted , the decimal point between m and p will also be removed.

·Example: In conversion instruction 10.2f, m is 10, p is 2, and X is f. If the conversion description is %10f, m is 10, p is omitted along with the decimal point, and if the conversion description is %.2f, p is 2, and m is omitted.

In the conversion description %m.pX , m specifies the minimum number of characters to be displayed, which is called the minimum column width. (can be understood as the total number of characters displayed in the output m)

* If the number of characters to be displayed is less than m, the value is right-justified in the field (add a space in front of the value to make up the number) , for example: %4d will display the number 123 in the form of 123 (add a space before 123 ).

* If the number of values ​​to be displayed is more than m, the column width will automatically expand ; for example: %4d will display the number 12345 in the form of 12345 without losing the digits.

* Adding a negative sign before m will cause the displayed value to be left aligned ; for example: %-4d will display 123 in the form of 123 (there is a space after 123)

In the conversion description %m.pX , p is called the precision. (In floating-point numbers, p digits after the decimal point can be represented.) It depends on the selection of the conversion specifier X, which indicates what kind of conversion needs to be performed on the value before it is displayed. Here are some commonly used conversion specifiers (the comprehensive table will be introduced in detail later)

*d - represents an integer in decimal form. p specifies the minimum number of values ​​to be displayed (if missing, add an extra zero before the number)

*e - Represents a floating point number in exponential (scientific notation) form. p specifies the number of digits that should appear after the decimal point (default value is 6). If p is 0, no decimal point is displayed.

*f - represents a floating point number without exponent, p has the same meaning as the specifier e.

*g——Represents a floating-point number in exponential form or fixed-point decimal form. The choice of form depends on the size of the number . p means the maximum number of significant digits that can be displayed (not numbers after the decimal point). Unlike f, the conversion of g will not display trailing zeros (if the value to be displayed by g does not have a decimal point After the number, g will not display the decimal point). When displaying numbers of moderate size, g uses fixed-point decimal; when displaying very large or very small numbers, g is converted to exponential form.

    int i;
	float x;
	i = 40;
	x = 200.20f;
	printf("|%d|%5d|%-5d|%5.3d|\n", i, i, i, i);
	printf("|%10.3f|%10.3e|%-10g|\n", x, x, x);

Output result: 

 

 Analysis:

·%d - Display variable i in decimal form, occupying the least space.

·%5d - displays variable i in decimal form and takes up at least 5 characters of space. Because i only occupies 2 characters, 3 spaces are added in front.

·%-5d - Display variable i in decimal form and occupy at least 5 characters of space. Because the value of i does not need to be 5 characters long, spaces are added at subsequent positions (numbers are left aligned).

%5.3d - displays variable i in decimal form, takes up at least 5 characters of space, and has at least 3 digits. Because variable i is only 2 characters long, an extra zero needs to be added to ensure that there are three digits ( Now it is only 3 characters long. To ensure that it occupies 5 characters, 2 spaces need to be added. Note that it is right-aligned)

·%10.3f - Display variable x in fixed-point decimal form, with a total of 10 characters, including 3 decimal places after the decimal point. Because variable x only requires 7 characters (counting the decimal point), 3 spaces are added in front.

·%10.3e - Display variable x in exponential form, with a total of 10 characters and 3 digits after the decimal point. The dependent variable x has 9 characters, so a space is added in front.

`%-10g——The variable x can be displayed in fixed-point decimal form or in exponential form, with a total of 10 characters. Because the number is small, fixed-point decimal form is selected, left-justified, followed by 4 spaces .

3. Escape sequence

 The \n commonly used in format strings is called an escape sequence. Escape sequences often contain some special characters without causing compiler errors. These characters include non-printing control characters and some characters with special meanings. Let’s first introduce some commonly used escape characters:

*Alarm bell symbol: \a //will produce a sound

*Return character: \b //will cause the cursor to return one position from the current position

*Line break:\n //will cause the cursor to jump to the beginning of the next line

*Horizontal tab: \t //will move the cursor to the next tab position (generally speaking, the distance between horizontal tabs // is 8 characters long, meaning to complete the current length to 8, But it also depends on the // operating system you are using, usually an integer multiple of 8)

* represents the character ":\" //Display the output character "

 

·The following figure shows the effects of horizontal tabs and line breaks: 

printf("Item\tUnit\tPutchase\n\tPrice\tDate\n");

 Output result: You can see that the horizontal tab character occupies 8 characters in length (including the output character itself, if it is less than 8 characters, add 4 spaces)

 

·If you want to display " ": 

printf("\"Hello!\"");

 Output result: 

 

 4. scanf function

*Like printf, scanf also reads input according to a specific format. The format string of scanf can also contain two parts: ordinary characters and conversion instructions .

*In many cases, the format string of the scanf function only contains conversion instructions, for example: scanf ("%d %d",&i,&j); Assume the user inputs 1 -2

 The function of the scanf function is to read the user input information, and then assign values ​​1-2 to variables i and j respectively.

*It should be noted that: first: when using the scanf function, you must check whether the number of conversion instructions matches the number of input variables, and check whether each conversion corresponds to a variable; second: & is usually placed before each variable , be sure not to forget, except in special circumstances (when it itself represents address information, because & means to get the address).

Reinterpretation of the meaning of scanf 

 The scanf function is essentially a "pattern matching" function that attempts to match input characters with conversion instructions. When the scanf function is called, scanf processes the information in the string starting from the left end. For each conversion description, the scanf function locates the matching item and skips spaces if necessary. Then scanf continues to read the input item until it encounters Stop reading when characters that cannot be matched are reached, and the remaining characters are handed over to the next scanf for reading.

Let's look at a very confusing example: 

    int i, j;
	float x, y;
	scanf("%d%d%f%f", &i, &j, &x, &y);
	printf("i=%d,j=%d,x=%f,y=%f", i, j, x, y);

Here we enter 1-20.3-4.0e3\n

Output result: 

 

explain:

*Conversion description %d: The first non-null input character is 1, and the integer can start from 1, so scanf continues to read downwards. When encountering -, scanf determines that the negative sign does not match the integer %d conversion description, so Store 1 in i and put - back.

*Conversion description %d: Then scanf reads -, 2, 0 and ., scanf successfully reads the -20 integer and stores it in j. When a decimal point is encountered, it does not match the conversion description, and the character . is put back to its original position.

*Conversion instructions %f: scanf reads ., 3, - characters. Because there cannot be a negative sign after a floating point number, scanf stores 0.3 in x. -Put it back in its original place.

*Conversion description %f: Finally, scanf reads -, 4, ., 0, e, 3 and newline characters. Because floating point numbers do not include newline characters, scanf stores -4.0*10 to the third power in y and puts the newline characters into y. The character is put back into its original place (buffer, we will introduce it in detail next time), leaving it for the next scanf call.

*Note: When using scanf, you must pay attention to format matching. When reading a string, scanf() will stop reading as long as it encounters a space, so "this is test" is three for scanf() String; another example: in scanf ("%d, %d", &i, &j);, the scanf function first looks for a suitable input integer and stores it in i, and then scanf tries to match the comma with the next input character. If If the next character is a space instead of a comma, the scanf function will terminate the operation and no longer read the value of j.

We will continue to provide further interpretations of input and output in the future. Thank you all for reading! ! ! If you have any questions, please feel free to comment and provide support in the comment area! ! !

 

 

 

 

 

Guess you like

Origin blog.csdn.net/m0_74475605/article/details/132049500