当前位置:网站首页>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 .
边栏推荐
- Feign & Eureka & Zuul & Hystrix 流程
- A Fletter version of Notepad
- 软件测试中功能测试流程
- In the next stage of digital transformation, digital twin manufacturer Youyi technology announced that it had completed a financing of more than 300 million yuan
- Use of shutter SQLite
- PG基础篇--逻辑结构管理(触发器)
- ZABBIX 6.0 source code installation and ha configuration
- Have you ever encountered the problem that flynk monitors the PostgreSQL database and checkpoints cannot be used
- Jenkins+webhooks-多分支参数化构建-
- Professor Li Zexiang, Hong Kong University of science and technology: I'm wrong. Why is engineering consciousness more important than the best university?
猜你喜欢

Manage nodejs with NVM (downgrade the high version to the low version)

路由基础之OSPF LSA详细讲解

How can genetic testing help patients fight disease?
基于mysql乐观锁实现秒杀的示例代码

shell脚本导入存储过程到数据库

Cs5268 advantages replace ag9321mcq typec multi in one docking station scheme

Wave animation color five pointed star loader loading JS special effects
![[today in history] July 1: the father of time sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world](/img/41/76687ea13e1722654b235f2cfa66ce.png)
[today in history] July 1: the father of time sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world

香港科技大学李泽湘教授:我错了,为什么工程意识比上最好的大学都重要?
![[Niu Ke's questions -sql big factory interview real questions] no2 User growth scenario (a certain degree of information flow)](/img/a0/e9e7506c9c34986dc73562539c8410.png)
[Niu Ke's questions -sql big factory interview real questions] no2 User growth scenario (a certain degree of information flow)
随机推荐
JS discolored Lego building blocks
Feign & Eureka & Zuul & Hystrix 流程
Feign & Eureka & zuul & hystrix process
C language learning
Three questions about scientific entrepreneurship: timing, pain points and important decisions
科学创业三问:关于时机、痛点与重要决策
Update a piece of data from the database. Will CDC get two pieces of data with OP fields D and C at the same time? I remember before, only OP was U
Detailed explanation of parallel replication examples in MySQL replication
一款Flutter版的记事本
[today in history] July 1: the father of time sharing system was born; Alipay launched barcode payment; The first TV advertisement in the world
CV顶会最佳论文得主分享:好论文是怎么炼成的?
请问flink mysql cdc 全量读取mysql某个表数据,对原始的mysql数据库有影响吗
I spent tens of thousands of dollars to learn and bring goods: I earned 3 yuan in three days, and the transaction depends on the bill
Flinkcdc should extract Oracle in real time. What should be configured for oracle?
CS5268优势替代AG9321MCQ Typec多合一扩展坞方案
Will it affect the original MySQL database to read the data of a MySQL table in full by flick MySQL CDC
Development trend and market demand analysis report of China's high purity copper industry Ⓕ 2022 ~ 2028
mysql统计账单信息(下):数据导入及查询
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
MySQL报错1040Too many connections的原因以及解决方案