当前位置:网站首页>3. Input and output functions (printf, scanf, getchar and putchar)
3. Input and output functions (printf, scanf, getchar and putchar)
2022-07-06 13:42:00 【It's Wang Jiujiu】
Catalog
printf The general format of the function
scanf The general format of the function
getchar Functions and putchar function
getchar The general format of the function
putchar The general format of the function
stay C In language ,scanf and printf Are input and output functions , When using these two functions , You need to specify the format of the input data , Specify different formats according to different types of data .
printf function
printf The general format of the function
printf(" Format control ", Output list )
Format control : A string enclosed in double quotation marks , There are two messages —— Format declaration and ordinary characters .
- Format statement : from % And format characters , for example %d,%c,%s etc. .
- Ordinary character : Ordinary characters keep their original appearance when outputting .
Output list : Data to be output , It can be a constant 、 Variable 、 Or an expression .
Sometimes in order to output beautiful , Some escape characters will be added to the format control , For example, add a newline character at the end .
utilize printf When a function outputs multiple variables , The order of format declaration should be consistent with the order of output list .
#include<stdio.h>
int main()
{
int a = 10;// integer
double b = 2.0;// Double precision
float c = 2.0f;// Single precision , When entering single precision , Add... At the end f, Otherwise, the compiler defaults to double type
printf("a=%d,b=%lf,c=%f\n", a,b,c);// When outputting multiple variables , The order of format declaration should be consistent with the order of output list
return 0;
}
When the output list is an expression , Try to make the expression concise , Don't over nest .
int sum(int x,int y)
{
return x + y;
}
#include<stdio.h>
int main()
{
int a = 10;
int b = 20;
printf("sum=%d\n",a+b);
printf("sum=%d\n", sum(a, b));// Expressions come in many forms , You can experiment by yourself
return 0;
}
Format characters
At output time , Different format declarations should be specified for different types of data .
The general form of format declaration can be expressed as :% Additional characters Format characters
( example :%5d Indicates that the field width is 5 The integer of ;%.2f To keep two decimal places decimal )
notes : Additional characters may not be displayed , however % And format characters are required .
Format characters | explain |
---|---|
d | Output signed decimal integer |
ld | Output signed decimal integer ( Long integer ) |
u | Output unsigned decimal integer |
c | Output a character |
s | Output string |
f | Output in decimal form , Single precision |
lf | Output in decimal form , Double precision |
p | Address |
g | When output in decimal form , Do not output meaningless 0 |
e,E | Output real numbers in exponential form . use e It means (1.2e+02) use E It means (1.2E+02) |
o | Output integer in octal unsigned form |
x,X | Output an integer in hexadecimal unsigned form use x Output in lowercase letters ; use X Output in capital letters . |
character | explain |
l | For long integers 、 Double decimal , Can be added to the formatter d、o、x、u、f front |
m | m Expressed as the minimum width of data (m Is a positive integer ) |
.n | For real numbers ,.n For output n Decimal place The string ,.n Is the number of characters intercepted (n Is a positive integer ) |
- | The output numbers or characters are left aligned in the field |
matters needing attention
1、printf Function output , The output object must match the corresponding type .
2、 Except for specific format characters , Other format characters must be lowercase .
3、 stay printf Functional “ Format control string ” Escape characters can be added to .
4、 Format characters are in % Start with , End with one of the format characters in the above .
5、 If you want to output %, belong “ Format control string ” Use two in succession “%” Express .
for example :printf("%d%%",10); The output is 10%
6、 If the content you want to output is confused with escape characters , Add \ that will do .
for example : How to output a \n Well ? answer :printf("\\n");
7、printf The function has a return value , Its return type is integer , The size is the number of printed contents .
scanf function
scanf The general format of the function
scanf( Format control , Address table column )
Format control : Meaning with printf function .
Address table column : Is a table column composed of several addresses , It could be a variable 、 The first address of the string .
The general form of the address table column is & Parameter name , here & To get the address symbol .
for example :int a = 0;
scanf("%d",&a);
matters needing attention
(1)scanf Function controls the format of the string according to the format , The corresponding input methods are also different , also scanf Format control of , Don't add escape characters at will , Will cause input errors .
for example :
int main()
{
int a = 0, b = 0, c = 0;
// Suppose we want to enter a=10,b=20,c=30
scanf("a=%d,b=%d,c=%d", &a, &b, &c);//a=10,b=20,c=30
printf("a=%d,b=%d,c=%d\n", a, b, c);
printf("--------------\n");
scanf("%d,%d,%d", &a, &b, &c);//10 20 30( Use... Between each number , separate )
printf("a=%d,b=%d,c=%d\n", a, b, c);
printf("--------------\n");
scanf("%d%d%d", &a, &b, &c);//10 20 30( Each number is separated by a space or a carriage return )
printf("a=%d,b=%d,c=%d\n", a, b, c);
return 0;
}
(2) When entering a value , You need to insert a space or enter between two values , So that the system can distinguish two values . But when inputting characters consecutively , Do not insert spaces or other separators , The system can distinguish two characters .
for example :
#include<stdio.h>
int main()
{
char c1 = { 0 };
char c2 = { 0 };
char c3 = { 0 };
scanf("%c%c%c", &c1, &c2, &c3);// Connected input abc Three characters , Press enter to finish
printf(" The correct result is :%c%c%c\n", c1, c2, c3);
printf("------\n");
getchar();// Take a character from the buffer
scanf("%c%c%c", &c1, &c2, &c3);// Input abc Three characters , Each character is separated by a space
printf(" The wrong result is :%c%c%c\n", c1, c2, c3);//err
return 0;
}
Press F10 Enter debugging , Open the monitoring panel , Yes c1、c2、c3 To monitor .
Find out c1 To be an assignment ‘a’,c2 Assigned by ‘ ’,c3 To be an assignment ‘b’. When entering consecutive characters , Do not add spaces .
(3) When inputting numerical data , Enter characters that are not numeric ( for example : Space 、 enter 、Tab etc. ), Think the data is over .
#include<stdio.h>
int main()
{
int a = 0;
char b = { 0 };
float c = 0.0f;
scanf("%d%c%f", &a, &b, &c);
printf("a=%d b=%c c=%f\n", a,b,c);
return 0;
}
Assume that the input 1234z78 .23, The first integer value is read 1234, To ‘z’ When you find a non numeric character, you stop ; The second character reads exactly one ‘z’; The third floating-point value is read 78, To ‘ ’ Stop reading when non numeric characters are found .
(4) use scanf Function to enter an array
#include<stdio.h>
int main()
{
int arr[10] = { 0 };
int i = 0;
for(i = 0; i < 10;i++)
{
scanf("%d", &arr[i]);
}
for (i = 0; i < 10; i++)
{
printf("%d", arr[i]);
}
return 0;
}
In the compiler , The subscript of an array is from 0 At the beginning , That is, the subscript of the first element is 0, The second element subscript is 1....... The subscript of the tenth element is 9. Here, for the input of array, we can use for Loop through the input , Input one element of the array at a time , Until the entire array is input , The same is true for printing arrays .
notes : When the array is a string , You can input 、 Output , And because the array name is the address of the array , So call scanf You don't have to add & Symbol .
for example :
#include<stdio.h>
int main()
{
char arr[10] = { 0 };
scanf("%s", arr);
printf("%s", arr);
return 0;
}
getchar Functions and putchar function
except printf and scanf Output and input characters ,C The library functions of the language also have functions specially used for inputting and outputting characters .
getchar The general format of the function
getchar The function gets a character from the buffer , Its return type is integer .
getchar function ( Character input function ) The general form of :getchar()
notes :getchar The return type of the function is integer , When getchar After reading or reading failure, it will return EOF,EOF The size of is actually -1, So you need to create an integer variable to receive getchar.
putchar The general format of the function
putchar The function outputs a character to the display , The integer of its return type .
putchar function ( Character output function ) The general form of :putchar(a)( It means output variable a The characters of )
notes :putchar(a) Medium a Can be character constants 、 integer constants 、 Character variable or integer variable ( Its value is in the... Of the character ASCII Within the scope of the code )
getchar Use of functions
It is mainly used to clean the buffer .
scanf and getchar Functions read data from buffers , Just talk about scanf Take the code of , For example, we want to enter 3 Characters , Namely ‘a’、‘b’、‘c’, When we're done typing abc after ,scanf Cannot read , We also need to hit the Enter key , After the data goes into the buffer ,scanf In order to read .
#include<stdio.h>
int main()
{
char c1 = { 0 };
char c2 = { 0 };
char c3 = { 0 };
scanf("%c%c%c", &c1, &c2, &c3);// Connected input abc Three characters , Press enter to finish
printf(" The correct result is :%c%c%c\n", c1, c2, c3);
printf("------\n");
getchar();// Take a character from the buffer
scanf("%c%c%c", &c1, &c2, &c3);// Input abc Three characters , Each character is separated by a space
printf(" The wrong result is :%c%c%c\n", c1, c2, c3);//err
return 0;
}
In the buffer , Except what we want abc, And what we left when we hit the Enter key \n, If you only input data once, it will not have any impact . But what if we want to input two numbers in succession ? Suppose I want to enter... For the second time ‘d’、‘e’、‘f’. the second scanf First, it will read the data left in the buffer \n.
At this time , the second scanf First, I will read what I left behind \n, And then there was de. Want to solve this problem , It only takes two times scanf Add... Between getchar(), Take away the line break .
However ,gerchar() Only one character can be taken away at a time , If you need to take away more than one character ?
while ((ch = getchar()) != '\n')// Clean buffer
{
}
while Recycle all the time getchar Read character , Until I read \n when , Buffer cleanup complete .
for example :
Make a simple password input program
#include<stdio.h>
int main()
{
char arr[10] = { 0 };
printf(" Please input a password :>");
scanf("%s", arr);
int ch = 0;
while ((ch = getchar()) != '\n')// Have been use getchar Read the characters in the buffer , Until I read \n when , Buffer cleanup complete
{
}
printf(" The password is %s\n Confirm please press 1, To cancel, please press 0\n",arr);
int ret = 0;
again:
scanf("%d", &ret);
switch (ret)// Select statement
{
case 1:
printf(" Confirm success \n");
break;
case 0:
printf(" Cancellation successful \n");
break;
default:
printf(" Input error , Re input \n");
goto again;// If the input is wrong , Jump back again Come back
}
return 0;
}
Set up a char An array of types , Suppose you accidentally enter a space when entering your password , for example w123 456, that getchar I'll take the back 456 Read go , It doesn't affect the back scanf The input of .switch and goto The sentence will be learned later .
putchar Use of functions
putchar Function can output characters displayed on the display , You can also input screen control characters .
for example :putchar(‘\n’) The function of is to wrap lines on the screen , The functions and printf("\n") equally .
#int main()
{
char a = 'a', b = 'b', c = 'c';
int a1 = 97, b1 = 98, c1 = 99;
putchar(a);// Output characters directly
putchar(b);
putchar(c);
putchar('\n');// Two line breaks
printf("\n");
putchar(a1);// utilize ASCII Code output character (putchar The way )
putchar(b1);
putchar(c1);
putchar('\n');
printf("\n");
printf("%c", a1); // utilize ASCII Code output character (printf The way )
printf("%c", b1);
printf("%c", c1);
return 0;
}
By the above example , We also found that ,putchar You can use ASCII Code value print character , As long as its value is ASCII Within the range of code (0~127). and printf There are also uses ASCII Code output character mode , The output results of the above three methods are consistent .
notes : because putchar Is a function of character output , therefore putchar(97) Output only ‘a’, Instead of outputting integers 97.
边栏推荐
猜你喜欢
随机推荐
Floating point comparison, CMP, tabulation ideas
Caching mechanism of leveldb
Questions and answers of "Fundamentals of RF circuits" in the first semester of the 22nd academic year of Xi'an University of Electronic Science and technology
受检异常和非受检异常的区别和理解
【九阳神功】2021复旦大学应用统计真题+解析
The difference between overloading and rewriting
[面试时]——我如何讲清楚TCP实现可靠传输的机制
C语言入门指南
IPv6 experiment
甲、乙机之间采用方式 1 双向串行通信,具体要求如下: (1)甲机的 k1 按键可通过串行口控制乙机的 LEDI 点亮、LED2 灭,甲机的 k2 按键控制 乙机的 LED1
[graduation season · advanced technology Er] goodbye, my student days
fianl、finally、finalize三者的区别
使用Spacedesk实现局域网内任意设备作为电脑拓展屏
Have you encountered ABA problems? Let's talk about the following in detail, how to avoid ABA problems
C language Getting Started Guide
This time, thoroughly understand the MySQL index
最新坦克大战2022-全程开发笔记-1
List set map queue deque stack
2022泰迪杯数据挖掘挑战赛C题思路及赛后总结
2.初识C语言(2)