c detailed explanation of formatted input and output

The content after the% sign in the standardized input-output function has always been a mystery. Try to add up here. The parts that can be placed in the two functions are as follows:

printf() %[flags][width][.prec][hlL]type
scanf() %[flags]type

scanf() is simpler.

printf()

1 flag

flag meaning
- Align left
+ Put a sign in front (+ or -)
(space) Positive number left blank
0 0 padding
# Add identifiers 0x, 0 before hexadecimal and octal respectively

2 width

width meaning
number Minimum number of characters (length of the entire output)
* The next parameter is the number of characters
.number The number of digits after the decimal point
.* The next parameter is the number of digits after the decimal point

3 .pre

.pre meaning
.number The number of digits after the decimal point
.* The next parameter is the number of digits after the decimal point
printf("%- 6d\n",123);// - 左对齐, 整数前填充空格,, 输出6位 ,  
 123
printf("%+06d\n",-123); // 加符号, 0填充,。
-00123
printf("%+08.2f\n",123.1); // 加符号, 0填充, 共八个字符, 小数点后2位, 输出浮点型。
+0123.10
printf("%#+08.2x\n",12); // 添加进制标识符
    0x0c

Don't add-the default is right alignment. Obviously, 0 padding cannot be used after left alignment. The order of grammars at the same level is irrelevant.

4 modifier

Type modification meaning
hh Single byte
h short
l long
ll long
L long doubel

5 Type

Types of meaning
i or d int
u unsigned int
O Octal
x Hexadecimal
X Hexadecimal for uppercase letters
f or F float , 6
e or E index
g float
G float
a or A Hexadecimal floating point
c char
s String
p pointer
n Number of outputs or outputs
int num = 0; 
printf("hello world%n\n",&num); //%n的使用, 本地编译器不能使用%n, 在线编译器可以
printf("%d\n",num);
// 输出 
hello world
11

scanf()

1 scanf

flag meaning
* jump over
number Maximum number of characters
hh char
h short
l long, double
ll long long
L long double

2 scanf

type meaning
d int
i Integer, may be hexadecimal or octal
u unsigned int
O Octal
x Hexadecimal
a,e,f,g float
c char
s String
[…] Allowed characters
p pointer

The return value of printf() and scanf()

prinff() returns the number of characters output
scanf() returns the number of items input

Guess you like

Origin blog.csdn.net/weixin_43705953/article/details/115304823