3. Output printf() and input scanf()

input and output

1.printf()

1.1 Quotation conditions

The header file <stdio.h> must be introduced before using the printf() function.


1.2 About line breaks

printf() will not automatically wrap lines when printing, so you need to add the escape character \n, which is a newline character, at the end of the output text, otherwise the output result of the modulation will be uncomfortable to see.
You can also add \n in the middle of the text to break the line.

int main() {
    
    
	printf("我要换行!");
	printf("换了又好像没换。。。");
	printf("我要换行!\n");
	printf("真的换了!\n");
	
	printf("还能在\n文本\n里面换!");
	return 0;
}

Insert image description here


1.3 The f in the placeholder
printf means format, which means that the printf() function can format the output
The first character of the placeholder is the percent sign %, and the second character indicates the type of placeholder.
Different placeholders represent different data types. The position of the placeholder can be substituted with other values. It is a bit abstract. Let’s give an example directly.

//占位符
int main() {
    
    
	printf("字符:%c\n", '1');//占位符%c表示 这里代入的数必须为字符
	printf("整数:%d\n", 1);//占位符%d表示 这里代入的数必须为整数
	printf("字符串:%s\n", "1");//占位符%s表示 这里代入的数必须为字符串
	printf("浮点数:%f\n", 1.0);//占位符%f表示 这里代入的数必须为浮点数
}
	return 0;
}

Insert image description here
If the value is not substituted according to the data type of the corresponding placeholder, a warning + error will be reported. Even if the execution is successful, the output value will have various errors (garbled characters, no results, etc.)

There can be multiple placeholders in a piece of text

int main() {
    
    
	printf("今天考试考了%d分,花了%.2f元买了包烟,路上遇见老%c,他说:“%s", 0,9.99,'A',"抽你个棒棒锤!");
}

Insert image description here


Some commonly used placeholders and their meanings
Insert image description here


1.4 Limiting the width
printf() allows limiting the minimum width of the placeholder

%5d means that the width of this placeholder is at least 5 characters. If it is less than 5 digits, a space will be added in front of the corresponding value.
The output value is right-aligned by default, that is, there will be spaces on the left side of the output content.
If you want to change it to left alignment, that is, there will be spaces on the right side of the output content, you can insert a - sign after the % in the placeholder.

int main()
{
    
    
	//整数
	printf("%5d\n", 123); // 输出为 " 123"
	printf("%-5d\n", 123); // 输出为 "123  "
	printf("111111"); //开头和3会有两个空格差
	return 0;
}

Insert image description here

The decimal limit width is the same, but decimals retain 6 decimal places by default, so in the following case, the default output of 1.0 is 1.000000, which already occupies 8 digits, and two digits are added in front.

	//小数
	printf("%10f\n", 1.0); // 输出为"  1.000000"
	printf("%-10f", 1.0); // 输出为"1.000000  "
	printf("111111");

Insert image description here


1.5 Limit the number of decimal places

int main() {
    
    
	printf("绩点:%.2f\n", 3.555555);
	return 0;
}

Insert image description here
The %f placeholder retains 6 as a decimal by default. You can use a format similar to %.2f to limit the number of decimal places.


1.6 Limit width and limit decimal places can be used together

int main() {
    
    
	printf("%6.2f\n", 3.555);
	return 0;
}

Insert image description here
The width is at least 6, and there are two decimal places after the decimal point [][] There are two spaces before 3.56


1.7 Use * to replace width and decimal places

int main() {
    
    
	printf("%*.*f\n", 6,3,3.555);
	return 0;
}

Insert image description here
The results of printf(“%*.*f\n”, 6, 3, 3.555) and printf(“%6.2f\n”, 3.555) are the same


1.8 Placeholder %s outputs part of the characters
%s indicates that the substituted value must be a string. The default is to output all. If you only need to change part of the string, you can use%.[m]sSpecify the output length, where [m] represents a number, which indicates the length to be output

//%s 输出部分字符
int main() {
    
    
	printf("%.5s", "123456789");//12345
	return 0;
}

2.scanf()

2.1 Basic usage

int main()
{
    
    
	int score = 0;
	printf("请输入成绩:");
	//输入一个值
	scanf("%d", &score);

	//输出
	printf("%d", score);
	return 0;
}

As a result, a problem occurred and an error was reported (error code C4996)
Insert image description here

Reason: Scanf is considered unsafe when compiling in the IDE of vs, so scanf_s is used instead.
Note: However, scanf is still used in the C language standard library. It is useless to use scanf_s on other compilers.

Solution

Solution 1
: Replace scanf with scanf_s in vs.

Option 2 (recommended)
Add code to the first line of the current project (must be added to the first line)
#define _CRT_SECURE_NO_WARNINGS 1

#define  _CRT_SECURE_NO_WARNINGS

A once and for all solution:
There will be a newc++file.cpp file in the Visual Studio IDE\Common7\IDE\VC\VCProjectItems directory. This file
Insert image description here
is copied every time a new .c or .cpp file is created,
so find this file in this file. Add #define _CRT_SECURE_NO_WARNINGS 1 to the first line. Every time you create a new .c or .cpp file, this line of code #define _CRT_SECURE_NO_WARNINGS 1 will be included by default.

Option 3
: Add the code
#pragma warning(disable:4996)
and the error code reported is C4996
Insert image description here

Multiple variables can be entered at the same time. The corresponding order of each variable and placeholder must be consistent, and the data type defined by the placeholder must also be consistent.

 int main()
 {
    
    
	int a = 0;
	int b = 0;
	float f1 = 0;
	float f2 = 0;
	scanf("%d %d %f %f", &a,&b,&f1,&f2);
	//scanf("%d%d%f%f", &a,&b,&f1,&f2);//和上行代码相等,执行调式时输出依然要使用空格来隔开
	//scanf() 处理数值占位符时,会⾃动过滤空⽩字符,包括空格、制表符、换⾏符等
	
	printf("%d %d %f %f", a,b,f1,f2);
	return 0;
}

One or more spaces does not affect scanf()'s ability to interpret the data.
In addition, users can use the enter key, space bar, etc. to divide the input part into several paragraphs, which does not affect the interpretation.
Because each time you press Enter after entering a value, scanf() will start to interpret the placeholders in the order in which the Enter key is pressed.
Insert image description here

2.2 Return value of scanf The return value
of scanf() is an integer, indicating the number of successfully read variables.
If no item is read, or the match fails, 0 is returned.
If the data is read successfully before

 int main()
 {
    
    
	 int a = 0;
	 int b = 0;
	 float f1 = 0;
	 float f2 = 0;
	 int sum = scanf("%d %d %f %f", &a, &b, &f1, &f2);
	 printf("%d", sum);
	 return 0;
 }

All inputs are correct
Insert image description here

Enter two correct words, then directly ctrl+z (three) to exit and end early.
Insert image description here

If you don’t lose a single number, just ctrl+z to end, then output -1, which is EOF.
Insert image description here

2.3 Placeholder
%c: character.
%d: Integer.
%f: float type floating point number.
%lf: double type floating point number.
%Lf: long double type floating point number.
%s: string.
%[]: Specify a set of matching characters in square brackets (such as %[0-9]). When encountering characters that are not in the set, the matching will stop.

Except for %c, leading whitespace characters are automatically ignored.
%c does not ignore whitespace characters and always returns the current first character, regardless of whether the character is a space.

 int main()
 {
    
    
	 char ch = 0;
	 scanf("%c",&ch);
	 printf("%c",ch);
	 printf("xxx");//作为参照物
	 return 0;
 }

Enter [space]a here
and output [space]xxx
. Description: When the input placeholder is a character, only the first character is always read and spaces are not ignored.
Insert image description here

Regarding the placeholder %s, the rules for reading it with scanf():Read from before the first non-whitespace character to the first whitespace character encountered (i.e. space, newline, tab, etc.).
%s will not contain whitespace characters, so it is not suitable for reading strings that may contain spaces.

Note: When the scanf() function reads a string into a character array, it does not detect whether the string exceeds the length of the array.
Therefore, when using the %s placeholder, it is recommended to specify the maximum length of the read string.That is %[m]s, m is an integer, indicating the maximum length of the read string. Strings exceeding the length will be discarded.

//字符串%s占位符
 int main()
 {
    
    
	 char arr[8];//最大只能输7个字符 末尾还有一个转义字符\0
	 scanf("%3s", &arr);//输入限制在3个字符以内
	 printf("%s", arr);
	 return 0;
 }

Insert image description here

2.4 Assignment Ignore Character
As long as * is added after the percent sign of any placeholder, the placeholder will not return a value and will be discarded after parsing.

int main()
{
    
    
	int year = 0;
	int month = 0;
	int day = 0;
	scanf("%d%*c%d%*c%d", &year, &month, &day);
	printf("%d-%d-%d", year, month, day);
	return 0;
}

The two %c character placeholders sandwiched in the middle have an * added after the %, so they will be discarded after reading and parsing. Therefore,
no matter what the two separated characters are during input, it will not affect the result.
Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/qq_45657848/article/details/131876129