当前位置:网站首页>String input function
String input function
2022-07-01 13:15:00 【multydoffer】
One 、scanf
scanf Compared with the string input function in the conventional sense , More specifically, it is actually a word input function . because scanf The function specifies that the input starts with the first non null character , Until you encounter blank ( Space 、 Carriage return or tab ) Stop typing , So in essence, it can only input a word without spaces in the middle at one time .
Such as :
char a[10];
scanf("%s", a);Input good morning, Only good, And the rest of the characters “ morning\n” Will remain in the buffer (buffer) Inside , If the next string input function is still scanf, Then the function will skip morning The previous space , Start with the first non empty character . In fact, no matter morning How many blanks are there before ,scanf Will skip directly .
If the input line is too long , It is possible to erase the existing data , For details, you can learn about buffer . And in order to prevent the hidden danger of this clock , have access to
scanf("%10s", a);To control the read length of string input , such scanf Function will only read 10 Characters , Avoid danger . But overall scanf It is still inconvenient for ordinary string input .
Two 、gets
gets The parameters of the function only need the array name / Pointer name , And not like scanf In that case, you need to worry about blank affecting the input . And this function also helps you read the end of the input '\n' Delete and replace with '\0', It seems to be easy to use .
But we still face the problem that the input line is too long , The risk of erasing existing data . and gets The function itself has no effective preventive measures .C11 The Standards Committee abolished the standard directly gets function . And now that the standard has been released , Then the compiler must adjust what it supports according to the standard , I don't support anything . However, in practical application , In order to be compatible with earlier code , Most continue to support gets function .
But in general ,gets It's more convenient .
Is there a better function ?
3、 ... and 、gets_s
C11 newly added gets_s Function is its optional extension , The second parameter of this function is to limit the number of characters read . If the second parameter is n, At most n-1 Characters are read .
If we want to read 9 Characters , It can be written like this :
gets_s(words, 10);//words For a defined length >=10 Array of Be similar to gets function ,gets_s The function will not store line breaks , But abandon him .
But if gets_s The maximum number of characters in the function supervisor did not read line breaks , Will perform the following steps . First, set the first character in the target array to null character ‘\0’, Read and discard subsequent input until the line break or the end of the file , Then it returns a null pointer . next , Call the implementation dependent ” Processing function “, May abort or exit the program .
But in fact, you don't necessarily know how to write special ” Processing function “, So that's why gets_s Function is only an optional extension of the standard .
Four 、fgets
fgets The function solves the overflow problem by limiting the number of characters read through the second parameter . This function is specifically designed to handle file input , So it may not be easy to use in general .fgets and gets The difference is as follows :
1. fgets The function of the first 2 Two parameters indicate the maximum number of characters to read in . If the value of the parameter is n, that fgets Will read in n-1 Characters , Or until the first newline character encountered . With this gets_s Function similar to , but fgets There are no annoying abort program problems .
2. If fgets Read a newline , Will store it in a string . With this gets Different ,gets Line breaks are discarded .
3. fgets The third parameter of the function indicates the file to be read in . If you read in the data entered from the keyboard , with stdin( The standard input ) As a parameter , The identifier is defined in stdio.h in .
Deficiency 1. Consider the following situation
fgets(words, 14, stdin);
puts(words);Input :apple pie( enter )
The output :apple pie( Line break )+( Line break )
Why are there two line breaks ? The first is because fgets The function also stores line breaks in the array . The second is because puts The line break at the end of the function . Another inconvenient point .
Deficiency 2. If fgets The input of exceeds the limit of the second parameter at one time , Then the remaining characters will remain in the buffer , Further affect us .
So we think about , Read in '\n' Directly replace with '\0', And directly delete the part beyond the limit .
So there is a relatively excellent self built function .
5、 ... and 、s_gets
char * s_gets(char * st, int n)
{
char * ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if(ret_val)// Prevent reading to the end of the file or reading failure , Return null pointer null
{
while(st[i] != '\n' && st[i] != '\0')
i++;
if(st[i] == '\n')// Replace line breaks
st[i] = '\0';
else// Delete redundant input
while(getchar() != '\n')
continue;
}
return ret_val;
}Of course, this is only a relatively preliminary optimization . In fact, deleting redundant input may cause trouble in many other situations , This requires continuous learning , Improved .
边栏推荐
- How to count the status of network sockets?
- Router. use() requires a middleware function but got a Object
- mysql统计账单信息(下):数据导入及查询
- Declare an abstract class vehicle, which contains the private variable numofwheel and the public functions vehicle (int), horn (), setnumofwheel (int) and getnumofwheel (). Subclass mot
- Meta再放大招!VR新模型登CVPR Oral:像人一样「读」懂语音
- The popular major I chose became "Tiankeng" four years later
- Zabbix 6.0 源码安装以及 HA 配置
- CV顶会最佳论文得主分享:好论文是怎么炼成的?
- 终端识别技术和管理技术
- 彩色五角星SVG动态网页背景js特效
猜你喜欢

Shell script imports stored procedures into the database
![leetcode:226. Flip binary tree [DFS flip]](/img/b8/6c5596ac30de59f0f347bb0bddf574.png)
leetcode:226. Flip binary tree [DFS flip]

Google Earth Engine(GEE)——全球人类居住区网格数据 1975-1990-2000-2014 (P2016)

Meta再放大招!VR新模型登CVPR Oral:像人一样「读」懂语音

Based on the open source stream batch integrated data synchronization engine Chunjun data restore DDL parsing module actual combat sharing

JS discolored Lego building blocks

硬件开发笔记(九): 硬件开发基本流程,制作一个USB转RS232的模块(八):创建asm1117-3.3V封装库并关联原理图元器件

香港科技大学李泽湘教授:我错了,为什么工程意识比上最好的大学都重要?

王兴的无限游戏迎来“终极”一战

Function test process in software testing
随机推荐
MySQL Replication中的并行复制示例详解
从数据库中更新一条数据,用cdc会同时获得op字段分别为d和c的两条数据吗?我记得之前是只有op为u
商汤科技崩盘 :IPO时已写好的剧本
Run PowerShell script prompt "because running script is prohibited on this system" solution
Operator-1 first acquaintance with operator
彩色五角星SVG动态网页背景js特效
启动solr报错The stack size specified is too small,Specify at least 328k
Example code of second kill based on MySQL optimistic lock
一款Flutter版的记事本
be based on. NETCORE development blog project starblog - (13) add friendship link function
SQLAlchemy在删除有外键约束的记录时,外键约束未起作用,何解?
R language uses conf of yardstick package_ The mat function calculates the confusion matrix of the multiclass model on each fold of each cross validation (or resampling), and uses the summary to outpu
北斗通信模块 北斗gps模块 北斗通信终端DTU
Manage nodejs with NVM (downgrade the high version to the low version)
Who should I know when opening a stock account? Is it actually safe to open an account online?
Global and Chinese n-butanol acetic acid market development trend and prospect forecast report Ⓧ 2022 ~ 2028
Ikvm of toolbox Net project new progress
Scene function of wooden frame
Machine learning - performance metrics
Research Report on China's software outsourcing industry investment strategy and the 14th five year plan Ⓡ 2022 ~ 2028