当前位置:网站首页>Add an article ----- scanf usage
Add an article ----- scanf usage
2022-07-26 23:47:00 【Xiaotian who studies hard】
Hello!!! I'm here again , To write an article about scanf Usage of , Why put it here ? harm ---- Because there is a question about scanf The problem of , Make Xiaotian ( I ) Tangled for more than half an hour . Now let me show you my question , I hope you don't appear !!!
error


What's wrong ( After half an hour of observation ........)

correct

Blame yourself for not being good at learning …………( I want to understand it !!!!)
scanf
scanf() yes C An input function in a language . And printf The function is the same , Are declared in The header file stdio.h in , So in use scanf Function with #include <stdio.h>.( In some implementations ,printf Function and scanf Functions can be used without precompiled commands #include .) It's a format input function , That is to say, input the data into the specified variables from the keyboard according to the format specified by the user .
The function prototype
intscanf(constchar* restrict format,...);
The first argument to the function is the format string , It specifies the format of the input , According to the format specifier, the information of the corresponding position is parsed and stored in the corresponding pointer position in the variable parameter list . Each pointer must be non null , And it corresponds to the format characters in the string one by one .scanf The first parameter of is the string to be input and the placeholder to be read .scanf Subsequent parameters of , Is the variable address that is read and assigned in turn . The type and quantity of placeholders need to correspond to the type and quantity of subsequent parameters .
Return value
scanf The function returns the number of successfully read data items , When I read in the data, I encountered “ End of file ” Then return to EOF.
scanf("%d %d",&a,&b);The return value of the function is int type . If a and b Have been successfully read into , that scanf The return value of 2; If only a Successfully read into , The return value is 1; If a Read failed , The return value is 0; If you encounter an error or encounter end of file, The return value is EOF.end of file by Ctrl+z perhaps Ctrl+d
Format specifier
c Read a character sequence consisting of a specified number of characters in the field width ( There will be no empty bytes after it ), If the width is omitted, a single character is read . Such as %c or %1c Read in single characters ,%2c Read in two characters ( There will be no empty bytes after it ), And so on .
s Read in a sequence of characters , It will be followed by bytes , Encountered white space character (\t \r \n Spaces, etc. ) Finish read .
d Read in optional signed ( Optional symbols indicate that you can enter with or without symbols , If there is no sign, it is regarded as non negative ) Decimal integer . The input format should be like strtol Functional base The argument is 10 The character sequence recognized when calling is the same .
u Read in unsigned decimal integers . The input format should be like strtol Functional base The argument is 10 The character sequence recognized when calling is the same .
p Read into one The pointer value . The read character sequence should match fprintf Of %p The resulting character sequence has the same form .
Just know the following ( above Understand and be able to use )
i Read in optional signed integers . The input format should be like strtol Functional base The argument is 0 The character sequence recognized when calling is the same .
a,e,f,g,A,E,F,G Read in optional signed floating-point numbers , The input format should be like strtod The character sequence recognized by the function is the same .
o Read optional signed octal integers . The input format should be like strtoul Functional base The argument is 8 The character sequence recognized when calling is the same .
x,X Read optional signed hexadecimal integers . The input format should be like strtoul Functional base The argument is 16 The character sequence recognized when calling is the same .
n Don't read any characters , Instead, the number of characters read to this position is stored in the corresponding int* Point to . If this conversion specifier has * Or with domain width information ( Such as :%*n or %3n etc. ), Then the consequences are undefined .
Scan character sets
% Read in % Symbol ( Percent sign )
An invalid conversion specifier will cause undefined behavior .
Length modifier
hh And d, i, o, u, x, X, or n In combination with , Means corresponding to a signed char or unsigned char data .
h And d, i, o, u, x, X, or n In combination with , Means corresponding to a short int or unsigned short int data .
l And d, i, o, u, x, X, or n In combination with , Means corresponding to a long int or unsigned long int data ;
ll And d, i, o, u, x, X, or n In combination with , Means corresponding to a long long int or unsigned long long int data .
long a = 10; scanf("%ld",&a);
Blank character
White space makes scanf Function omits one or more white space characters in the input during a read operation .
The white space in the control string makes scanf() Skip one or more blank lines in the input stream . Whitespace can be a space (space)、 tabs (tab) And the new line (newline). Essentially , The white space in the control string makes scanf() Read... In the input stream , But don't save the results , Until you find non blank character until .
#include<stdio.h> int main() { int a = 0; int b = 0; scanf("%d %d", &a, &b);// Data cannot be separated by commas , Only white space characters can be used ( Space or tab Key or enter key ) Separate , for example :2 3 printf("%d %d\n", a, b); return 0; }
Nonwhite space character
A non white space character will make scanf() Function to erase the same character as the non whitespace character on read in .
The non blank character makes scanf() Read a matching character in the stream and ignore it . for example ,"%d,%d" send scanf() Read in an integer first , Discard commas in reading , Then read another integer . If no match is found ,scanf() return .
#include<stdio.h> int main() { int a = 0; int b = 0; scanf("%d,%d", &a, &b);// When inputting data, you must add “,”, for example :2,3 printf("%d %d\n", a, b); return 0; }
The format command can describe the maximum Domain width . At the percent sign (%) The integer between and format code is used to limit the maximum number of characters read in from the corresponding field . for example , Hope to address Read no more than 3 In characters , It can be written in the following form :
scanf("%3s",arr);If the content of the input stream is more than 3 Characters , The next time scanf() Read in from the stop . If a blank character has been encountered before reaching the maximum field width , Then the read to the field stops immediately ; here ,scanf() Jump to the next domain .
Although the space 、 tabs And newline are used as field segmentation symbols , But in the operation of reading single character, it is treated as normal character . for example , For the input stream "x y" call :
scanf("%c%c%c",&a,&b,&c);After the return ,x In variables a in , Spaces in variables b in ,y In variables c in .
matters needing attention
- For string arrays or string pointer variables , Because the array name can be converted into array and pointer, the variable name itself is the address , Therefore use scanf() Function time , You don't need to add... Before them "&" The operator .
- Can be in the format string "%" Add an integer between the format specifiers , Represents the maximum number of digits in any read operation .
- scanf There is no similar in the function printf Precision control of .
- Such as : scanf("%5.2f",&a); It's illegal. . You cannot attempt to enter a decimal as 2 The real number of bits .
scanf Variable address is required in , If you give a variable name, there will be an error
Such as scanf("%d",a); It's illegal. , Should be changed to scanf("%d",&a); It's legal .
When inputting multiple numerical data , If there is no non Format characters Make the interval between input data , You can use a space ,TAB Or enter to make an interval .
C The compiler encountered a space ,TAB, Carriage return or illegal data ( If yes “%d” Input “12A” when ,A It's illegal data ) The data is considered to be over .
In the input character data (%c) when , If there are no non format characters in the format control string , All the characters entered are considered to be valid . Such as :"%c" Input ' ' The space is also called
scanf("%c%c%c",&a,&b,&c);Input is :d e f
Then put 'd' give a, ' '( Space ) give b,'e' give c. because %c Only one is required to read character , There is no need to use a space as the space between two characters , So the ' ' Send it as the next character b. Only if the input is :def( No spaces between characters ) when , To put 'd' be endowed with a,'e' give b,'f' give c. If you add spaces as intervals in the format control .
scanf("%c %c %c",&a,&b,&c);Space can be added between the data when input .
problem
- How to make scanf() Function correctly accepts a string with spaces ? Such as : I love you!
#include <stdio.h> int main(void) { char str[80]; scanf("%s",str); printf("%s",str); return 0; }
Input :
I love you!
Output :
I
The above procedure does not achieve the expected purpose . because scanf Scan to "I" The following space is right str End of scan ( Spaces are not scanned ), And ignore the following " love you!".
reason
#include<stdio.h> #include<windows.h> int main(void) { char str[80],str1[80],str2[80]; scanf("%s",str);/* Input here :I love you!*/ printf("%s\n",str); Sleep(5000);/* Wait here 5 second , Tell you where the program runs */ /** * No sleep(5) *1, The function name is Sleep No sleep. * 2,Windows API in ,unsigned Sleep(unsigned) It should be milliseconds ms. */ scanf("%s",str1);/* You don't have to type in these two sentences , It's right stdin Stream rescan */ scanf("%s",str2);/* You don't have to type in these two sentences , It's right stdin Stream rescan */ printf("%s\n",str1); printf("%s\n",str2); return 0; }Input :
I love you!
Output :
I
love
you!Okay , I see why , So the conclusion is : Residual information love you It exists in stdin Streaming , Not on the keyboard buffer in .
correct
#include<stdio.h> int main(void) { char str[50]; scanf("%[^\n]",str);/*scanf("%s",string); Cannot receive space characters */ printf("%s\n",str); return 0; }
- keyboard buffer Residual information problem
#include<stdio.h> int main(void) { int a; char c=0; while(c!='N') { scanf("%d",&a); scanf("%c",&c); printf("a=%dc=%c\n",a,c);/*printf("c=%d\n",c);*/ } return 0; }scanf("%c", &c); This sentence can't receive characters properly , What's the reason ? We use it printf("c = %d\n", c); take C use int Express it , Enable printf("c = %d\n", c); This sentence , have a look scanf() Function to C What is it , The result is c=10 ,ASCII The value is 10 What is it? ? The new line is \n. by the way , Every time we hit "Enter" key , To keyboard buffer Send one “ enter ”(\r), One “ Line break "(\n), ad locum \r By scanf() The function takes care of ( Let's just say that ^_^), and \n By scanf() function “ error ” The earth bestows on c. terms of settlement Can be in two scanf() Add getchar(), But it depends scanf() Sentence plus that
#include<stdio.h> int main(void) { int a; char c=0; while (c != 'N') { scanf("%d", &a); getchar(); scanf("%c", &c); printf("a=%d c=%c\n", a, c);/*printf("c=%d\n",c);*/ } return 0; }
- The input type does not match the format string, resulting in stdin Blocking of flow .
#include<stdio.h> int main(void) { int a=0,b=0,c=0,ret=0; ret=scanf("%d%d%d",&a,&b,&c); printf(" First read in quantity :%d\n",ret); ret=scanf("%d%d%d",&a,&b,&c); printf(" The second read in quantity :%d\n",ret); return 0; }Input correctly :
But when the input content does not match the format string , The result will be surprising
Go to the first scanf when , When entering characters ’b’ Time and ret=scanf("%d%d%d",&a,&b,&c); The format string in does not match ,stdin The flow is blocked ,scanf Function is not reading the following part , Direct will 1 return , It means only will stdin Streaming 1 Read in the variable a in .
Go to the second scanf when , character ’b’ Still does not match the format string ,stdin The flow is still blocked , So there is no prompt to enter ,scanf Function will 0 return . correct
#include<stdio.h> int main(void) { int a=0,b=0,c=0,ret=0; ret=scanf("%d%d%d",&a,&b,&c); fflush(stdin);//fflush(stdin) Clear input buffer . printf(" First read in quantity :%d\n",ret); ret=scanf("%d%d%d",&a,&b,&c); fflush(stdin); printf(" The second read in quantity :%d\n",ret); return 0; }
- stay scanf("%d ",&a) %d Put a space after it
stay "%d" There is a %d Add one A space , This is the format when the program reads data , What does this format mean ? This format means after reading - After an integer , Spaces in the format also need to match secondary valid input , Just need to read another integer . Therefore, input 6 Data only read 5 individual . So remove the spaces in the format .
![]()
Conclusion :
There are only two truths in the world :1、 People are bound to die .
2、 The program must have Bug.
Thank you for watching !!!
边栏推荐
- Pytorch学习记录(二):张量
- What are the use cases in the Internet of things industry in 2022?
- Related functions of strings
- At 12:00 on July 17, 2022, the departure of love life on June 28 was basically completed, and it needs to rebound
- How to use data pipeline to realize test modernization
- 【C语言】经典的递归问题
- Everything you should know about wearable NFT!
- MVC three-tier architecture
- Typescript stage learning
- 第二部分—C语言提高篇_10. 函数指针和回调函数
猜你喜欢

第二部分—C语言提高篇_8. 文件操作

Disk expansion process and problems encountered in the virtual machine created by VMWare

Bid farewell to wide tables and achieve a new generation of Bi with DQL

Sign up now | frontier technology exploration: how to make spark stronger and more flexible

The NFT market pattern has not changed. Can okaleido set off a new round of waves?

C language array

Pytorch学习记录(二):张量

分页插件--PageHelper

About statefulwidget, you have to know the principle and main points!

Vector execution engine framework gluten announced the official open source and appeared at spark technology summit
随机推荐
数据供应链的转型 协调一致走向成功的三大有效策略
My SQL is OK. Why is it still so slow? MySQL locking rules
Machine learning notes - building recommendation system (3) six research directions of deep recommendation system
2022年物联网行业有哪些用例?
C language dynamic memory management
The memory occupation of the computer is too high after it is turned on (more than 50%)
[interview: concurrency 26: multithreading: two-phase termination mode] volatile version
【2016】【论文笔记】差频可调谐THz技术——
Positioning of soaring problems caused by online MySQL CPU
push to origin/master was rejected 错误解决方法
第二部分—C语言提高篇_9. 链表
Part II - C language improvement_ 11. Pretreatment
Simple SQL optimization
动态sql
New features of ES6
带你熟悉云网络的“电话簿”:DNS
Three person management of system design
JUnit、JMockit、Mockito、PowerMockito
How to use data pipeline to realize test modernization
【C语言】经典的递归问题


