preface

Speaking of C language I/O operation, learn C people’s first reaction must be printf/scanf function, that is the foundation of C language, program debugging skills :). Yes, as a C programmer, printf is the most frequently used function. But if I were to ask you how to format the input/output we want, you might be a little guilty. In order to fix this bug, today I will learn to format I/O with you.

Formatted output

The following is the standard family of output functions defined by ANSI C:

#include <stdio.h>

printf(char*format, ...) ;vprintf(const char *format, va_list arg);

sprintf(char *s, const char*format, ...) ;vsprintf(char *s, const char *format, va_list arg);

fprintf(FILE *stream, const char*format, ...) ;vfprintf(FILE *stream, const*format, va_list arg); . .Copy the code

As you can see, the difference between the above functions is (a: the output destination is different; B: The format of output content is different. But each function takes a format argument, which is used to format the final output. Let’s take printf as an example to explain how to control the format of its parameters through format.

The printf function controls the formatting of the corresponding parameters through the formatting item defined in format, and outputs the formatted content to the standard output device. Its return value is the number of characters printed.

The format argument includes two types of objects: plain characters and conversion descriptions. On output, the normal characters are printed as is, and the conversion description is used to control the formatting of the parameters in printf. Each conversion description begins with % and ends with a conversion character, such as the familiar %d, %s, etc., where d and s are the conversion characters. However, there are many control characters that can be added between % and the conversion character to achieve fine control over the output format.

Here are the definitions for the control character sections:

Control part: [- | | | + Spaces0|#][num][.][num][h|l|L]
Copy the code
character meaning
Specifies that the converted arguments are printed left aligned (right aligned by default)
+ Specifies to put a plus or minus sign in front of the output number
The blank space If the first character is not a plus or minus sign, it is preceded by a space
0 For numerical conversions, when the output length is less than the width of the segment, a leading 0 is added to fill
# Specify another form of output. If it is an O (octal) conversion, the first digit is 0. If it is x or x, then in front of a non-zero value, add either 0x or 0x
digital The specifiedMinimum field width. The converted parameter will print the field whose width is not less than the minimum field widthSpaces or 0 fill
The decimal point Used to separate field width from precision
digital Used to specify precision, that is, specifystringTo be printed inThe biggestNumber of characters,Floating-point decimal pointThe last digit,The integer leastThe number of digits to output
H or L or L H means to print the integer as short, the letter L means to print the integer as long, and the letter L means to print the integer as a long double

Here is the definition of the conversion character section:

character Parameter type; The output form
d,i The int type; The decimal system
o The int type; Unsigned octal book (no leading 0)
x,X The int type; Unsigned hexadecimal (no leading 0x or 0x), 10-15 is denoted by abcdef or ABCDEF, respectively
u The int type; Unsigned decimal number
c The int type; A single character
s Char *; Prints the characters in the string sequentially until ‘\0’ is encountered or the number of characters specified by precision has been printed
f Type double; Decimal decimal [-] M.ddddd, number of d controlled by precision (default is 6)
e,E Type double; [-]. M.ddddde ±xx or [-] M.ddddde ±xx, number of d controlled by precision (default: 6)
g,G Type double;
p Void * type; Pointer (implementation dependent)
% Do not convert parameters; Print a percent sign %
Except for e, e and g, which are not used very often, the other characters are used very frequently.

Here are a few examples of how the above conversion and control characters are used.

  1. Example 1: An integer is typed in hexadecimal. The output of other integers is similar

Ordinary printing:

printf("0x%x\n".1048576); Output:0x100000
Copy the code

If the integer is a memory address and the CPU is 32 bits, the print format is 0x00000001

printf("0x%.8x\n".1048576);//.8 indicates that the minimum number of digits to be output is 8orprintf("0x%08x\n".1048576);// Note: the Spaces where 08 is insufficient are filled with 0 to ensure a minimum width of 8 characters.Output:0x00100000
Copy the code
  1. Example 2: Use of H or L

Suppose the system is 32bit, int :4 bytes, long:4 bytes, long long:8 bytes

printf("%d\n".4294967295U);// Note that U cannot be omitted, otherwise it is treated as long. 4294967295:0xFFFF FFFFOutput:- 1

printf("%u\n".4294967295U); Output:4294967295

printf("%lu\n".4294967295UL); Output:4294967295

printf("%lld\n".4294967295L); Output:4294967295

printf("%hu\n".4294967295L);//h truncates 4294967295L to 65535Output:65535
Copy the code

The basic data types of the C language can be found here.

  1. Example 3: String output

The following table prints “Hello, world” (12 characters) in different formats.

printf(":%s:\n"."Hello, world");   | :Hello, world:
printf(":%10s:\n"."Hello, world");   | :Hello, world:
printf(":%.10s:\n"."Hello, world");   | :Hello, wor:
printf(":%.15s:\n"."Hello, world");   | :Hello, world:
printf(":%15s:\n"."Hello, world");   | :   Hello, world:
printf(":%-15s:\n"."Hello, world");   | :Hello, world   :
printf("% 15.10 s: \ n"."Hello, world");   | :     Hello, wor:
printf(": - 15.10% s \ n"."Hello, world");   | :Hello, wor     :
Copy the code
  1. Example 4: Decimal output

The decimal output is mainly a matter of precision, precision is 6 bits by default.

float f = 1.0 f/3;
printf("%.10f\n", f); Output:0.3333333433
Copy the code
  1. Example 5: Pointer output
int i  = 10;
printf("%p\n", &i); Output:0x7ffcf9e4f270
Copy the code
  1. Example 6: Width and precision can be replaced with asterisks in the transformation specification

If width and precision are replaced by *, the values of width and precision are computed by converting the next argument (which must be int). For example, to print the maximum number of characters from the string s, use the following statement:

printf("%.*s", max, s);// The printing accuracy of the string s is determined by the parameter Max
Copy the code

7. Example 7: Printf uses the first argument to determine the number and type of the following arguments. If the number of arguments is insufficient or the type is incorrect, you will get the wrong result. Notice the difference between the output of the following two function calls.

printf("%shello,world! \n");// If the string is printed with the character %, the output will fail.
printf("%s\n"."%shello,world!"); Output: hello, world! %shello,world!Copy the code

Other output functions, such as sprintf, fprintf, etc., are the same as the printf function, format each parameter after the format, the difference is that the output position is different, sprintf saves it in a character array, fprintf outputs it to a specific output stream.

To be continued… .

Reference: The C Programming Language, a book that every C programmer should read, pays tribute to the great fathers of Brian W.Kenighan and Dennis M.Ritchie!

For more quality content, please move to the public accountRunning yards