当前位置:网站首页>sscanf,sscanf_ S and its related usage "suggested collection"
sscanf,sscanf_ S and its related usage "suggested collection"
2022-07-07 04:33:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack .
#include<stdio.h>
Defined function int sscanf (const char *str,const char * format,……..);
Function description sscanf() Will set the parameter str The string of depends on the parameter format String to convert and format data . Please refer to scanf().
The converted results are stored in the corresponding parameters .
Return value If successful, the number of parameters is returned , Failure returns -1, The reason for the mistake lies in errno in . return 0 It means failure otherwise . Indicates the number of correctly formatted data such as :sscanf(str.”%d%d%s”, &i,&i2, &s); Suppose three changes are read successfully and will return 3. Suppose only the first integer is read into i Will return 1. Proof cannot be obtained from str Read in the second integer .
main() { int i; unsigned int j; char input[ ]=”10 0x1b aaaaaaaa bbbbbbbb”; char s[5]; sscanf(input,”%d %x %5[a-z] %*s %f”,&i,&j,s,s); printf(“%d %d %s ”,i,j,s); }
function 10 27 aaaaa
Everybody knows sscanf Is a very useful function , It can be used to extract integers from strings 、 Floating point numbers, strings, and so on . Its usage is simple , Especially for integers and floating-point numbers . But novices may not know some advanced usage when dealing with strings . Here's a brief explanation .
1. Common usage .
charstr[512]={0}; sscanf(“123456″,”%s”,str); printf(“str=%s”,str);
2. Takes a string of the specified length . As in the following example , Take the maximum length as 4 Byte string .
sscanf(“123456″,”%4s”,str); printf(“str=%s”,str);
3. Gets the string up to the specified character . As in the following example . Take the string until a space is encountered .
sscanf(“123456abcdedf”,”%[^]”,str); printf(“str=%s”,str);
4. Take the string containing only the specified character set . As in the following example , Only 1 To 9 And a string of lowercase letters .
sscanf(“123456abcdedfBCDEF”,”%[1-9a-z]”,str); printf(“str=%s”,str);
5. Gets the string up to the specified character set . As in the following example . Take the string until it encounters capital letters .
sscanf(“123456abcdedfBCDEF”,”%[^A-Z]”,str); printf(“str=%s”,str);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
You can use, for example, the following code to convert the string form ip The address is converted to four integers :
- char * inputIp
- int ip[4];
- sscanf_s(inputIp, “%d.%d.%d.%d”, &ip[0], &ip[1],&ip[2],&ip[3]);
Be careful sscanf_s. When the type read in is an integer or other type whose length can be determined . Cannot follow length after type , But for string types (char *) If the length is unknown, you must clearly indicate the maximum length of the string after the type ( That is, the space that can be accommodated ). For example, the following :
- // crt_sscanf_s.c
- // This program uses sscanf_s to read data items
- // from a string named tokenstring, then displays them.
- #include <stdio.h>
- #include <stdlib.h>
- int main( void )
- {
- char tokenstring[] = “15 12 14…”;
- char s[81];
- char c;
- int i;
- float fp;
- // Input various data from tokenstring:
- // max 80 character string plus NULL terminator
- sscanf_s( tokenstring, “%s”, s, _countof(s) );
- sscanf_s( tokenstring, “%c”, &c, sizeof(char) );
- sscanf_s( tokenstring, “%d”, &i );
- sscanf_s( tokenstring, “%f”, &fp );
- // Output the data read
- printf_s( “String = %s\n”, s );
- printf_s( “Character = %c\n”, c );
- printf_s( “Integer: = %d\n”, i );
- printf_s( “Real: = %f\n”, fp );
- }
For the case of reading multiple strings . The code is as follows :
- sscanf_s(inputString, “%s.%s.%s.%s”, s1, s1.length, s2, s2.length, s3, s3.length, s4, s4.length);
sscanf Functions work very well , Unexpectedly, I never knew this function . Recently, friends use VS2008 Use the safe version number of this function when typing code sscanf_s . But there are abnormal problems . Unable to parse string, don't say , It will collapse .
int sscanf_s( const char *buffer, const char *format [, argument ] … );
This is a MSDN The definition of function , I didn't continue to check the following notes , And examples . I can't feel it at all sscanf And sscanf_s The difference between . Thought it was still like sscanf The use of . So that strange problems appear .
Example:
// crt_sscanf_s.c
// This program uses sscanf_s to read data items
// from a string named tokenstring, then displays them.
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
char tokenstring[] = "15 12 14...";
char s[81];
char c;
int i;
float fp;
// Input various data from tokenstring:
// max 80 character string plus NULL terminator
sscanf_s( tokenstring, "%s", s, _countof(s) );
sscanf_s( tokenstring, "%c", &c, sizeof(char) );
sscanf_s( tokenstring, "%d", &i );
sscanf_s( tokenstring, "%f", &fp );
// Output the data read
printf_s( "String = %s\n", s );
printf_s( "Character = %c\n", c );
printf_s( "Integer: = %d\n", i );
printf_s( "Real: = %f\n", fp );
}
Until you finish reading the whole document , See this example , I found that there was something fishy !sscanf_s When I evaluate it . You need to specify the maximum size of the value after each value .
In the use of VS2005 When compiling a program , There are many warnings , It is said that the function used is unsafe . You should use a secure version number , That is, add function name “_s” Version number of . Warning content : warning C4996: ‘sscanf’: This function or variable may be unsafe. Consider using sscanf_s instead. according to the understanding of ,“_s” The version number function was later used by Microsoft c++ Expand . Used to replace the original unsafe function . such as :printf、scanf、strcpy、fopen wait .
Specific reference : ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.VisualStudio.v80.chs/dv_vccrt/html/d9568b08-9514-49cd-b3dc-2454ded195a3.htm
Function with the original security version number , Parameters and buffer boundaries are checked , Added return value and thrown exception . This adds function security , It reduces the chance of error . At the same time, this also means that when using these functions . Sometimes you have to enter many other parameters about the buffer size , A few more keystrokes can get less trouble . Worth !
Here is a summary of sscanf And sscanf_s Common usage of , Also embodies “_s” The difference between version number function and original function :
1、sscanf and scanf The difference is the input source . The former is a string , The latter is a standard input device
2、sscanf Use . Take parsing time strings as an example . The string “2009-01-02_11:12:13” It can be parsed as integer year, month, day, hour, minute and second
// Definition char cc; tm tm_temp={0}; string stime(“2009-01-02_11:12:13”);
//(1) It must be filled in strictly according to the separator form , If a mismatch is encountered, the resolution will be terminated
sscanf(stime.c_str(), “%4d-%2d-%2d_%2d:%2d:%2d”, &tm_temp.tm_year, &tm_temp.tm_mon, &tm_temp.tm_mday, &tm_temp.tm_hour, &tm_temp.tm_min, &tm_temp.tm_sec ); //(2) Can not be filled in according to the cutting symbol form , The number of characters must be consistent . For example, it can correctly parse “2009/01/02_11:12:13”
sscanf(stime.c_str(), “%4d%c%2d%c%2d%c%2d%c%2d%c%2d”, &tm_temp.tm_year, &cc, &tm_temp.tm_mon, &cc, &tm_temp.tm_mday, &cc, &tm_temp.tm_hour, &cc, &tm_temp.tm_min, &cc, &tm_temp.tm_sec ); //(3) Can not be filled in according to the cutting symbol form , The number of characters must be consistent . ditto ,%1s Can be equivalent to %c
sscanf(stime.c_str(), “%4d%1s%2d%1s%2d%1s%2d%1s%2d%1s%2d”, &tm_temp.tm_year, &cc, &tm_temp.tm_mon, &cc, &tm_temp.tm_mday, &cc, &tm_temp.tm_hour, &cc, &tm_temp.tm_min, &cc, &tm_temp.tm_sec );
//(4) Can not be filled in according to the form and quantity of the cutter , The type must be the same . For example, it can correctly parse “2009/01/02___11:12:13” // It's used here sscanf Regular expressions for , Similar to but not exactly the same as the general regular representation ,%*c Indicates that consecutive characters are ignored
sscanf(stime.c_str(), “%4d%*c%2d%*c%2d%*c%2d%*c%2d%*c%2d”, &tm_temp.tm_year, &tm_temp.tm_mon, &tm_temp.tm_mday, &tm_temp.tm_hour, &tm_temp.tm_min, &tm_temp.tm_sec ); 3、sscanf_s Use
// Definition char cc[2]; tm tm_temp={0}; string stime(“2009-01-02_11:12:13”);
//(1) And sscanf The first method is the same , Able to use ”%4d-%2d-%2d_%2d:%2d:%2d” Format matching parsing
sscanf_s(stime.c_str(), “%4d-%2d-%2d_%2d:%2d:%2d”, &tm_temp.tm_year, &tm_temp.tm_mon, &tm_temp.tm_mday, &tm_temp.tm_hour, &tm_temp.tm_min, &tm_temp.tm_sec ); //(2) Use %c Format when parsing data . The length parameter must be added to the corresponding buffer . Otherwise, there will be mistakes
sscanf_s(stime.c_str(), “%4d%c%2d%c%2d%c%2d%c%2d%c%2d”, &tm_temp.tm_year, &cc, 1, &tm_temp.tm_mon, &cc, 1, &tm_temp.tm_mday, &cc, 1, &tm_temp.tm_hour, &cc, 1, &tm_temp.tm_min, &cc, 1, &tm_temp.tm_sec ); //(3) Use %s Format when parsing data . Buffer length must be greater than string length , Otherwise, it will not be parsed
sscanf_s(stime.c_str(), “%4d%1s%2d%1s%2d%1s%2d%1s%2d%1s%2d”, &tm_temp.tm_year, &cc, 2, &tm_temp.tm_mon, &cc, 2, &tm_temp.tm_mday, &cc, 2, &tm_temp.tm_hour, &cc, 2, &tm_temp.tm_min, &cc, 2, &tm_temp.tm_sec );
//(4) And sscanf equally ,sscanf_s Regular expressions are also supported
sscanf_s(stime.c_str(), “%4d%*c%2d%*c%2d%*c%2d%*c%2d%*c%2d”, &tm_temp.tm_year, &tm_temp.tm_mon, &tm_temp.tm_mday, &tm_temp.tm_hour, &tm_temp.tm_min, &tm_temp.tm_sec ); Through the above comparison sscanf And sscanf_s Use , It can be seen that the latter has many other considerations about buffer security , So as to avoid a lot of inadvertent troubles .
Everybody knows sscanf Is a very useful function , It can be used to extract integers from strings 、 Floating point numbers, strings, and so on .
Its usage is simple . Especially for integers and floating-point numbers . But novices may not know some advanced usage when dealing with strings , Here's a brief explanation .
1. Common usage .
The following is a reference fragment : char str[512] = ; sscanf(“123456 “, “%s”, str); printf(“str=%sn”, str); |
---|
2. Takes a string of the specified length . As in the following example , Take the maximum length as 4 Byte string .
The following is a reference fragment : sscanf(“123456 “, “%4s”, str); printf(“str=%sn”, str); |
---|
3. Gets the string up to the specified character . As in the following example . Take the string until a space is encountered .
The following is a reference fragment : sscanf(“123456 abcdedf”, “%[^ ]”, str); printf(“str=%sn”, str); |
---|
4. Take the string containing only the specified character set . As in the following example . Only 1 To 9 And a string of lowercase letters .
The following is a reference fragment : sscanf(“123456abcdedfBCDEF”, “%[1-9a-z]”, str); printf(“str=%sn”, str); |
---|
5. Gets the string up to the specified character set .
As in the following example , Take the string until it encounters capital letters .
The following is a reference fragment : sscanf(“123456abcdedfBCDEF”, “%[^A-Z]”, str); printf(“str=%sn”, str);
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/116614.html Link to the original text :https://javaforall.cn
边栏推荐
- SQL where multiple field filtering
- Surpassing postman, the new generation of domestic debugging tool apifox is elegant enough to use
- 图灵诞辰110周年,智能机器预言成真了吗?
- Food Chem | in depth learning accurately predicts food categories and nutritional components based on ingredient statements
- Both primary and secondary equipment numbers are 0
- [multi threading exercise] write a multi threading example of the producer consumer model.
- [team learning] [phase 34] Baidu PaddlePaddle AI talent Creation Camp
- Dab-detr: dynamic anchor boxes are better queries for Detr translation
- 论文上岸攻略 | 如何快速入门学术论文写作
- 日常工作中程序员最讨厌哪些工作事项?
猜你喜欢
[team learning] [34 sessions] Alibaba cloud Tianchi online programming training camp
用CPU方案打破内存墙?学PayPal堆傲腾扩容量,漏查欺诈交易量可降至1/30
【线段树实战】最近的请求次数 + 区域和检索 - 数组可修改+我的日程安排表Ⅰ/Ⅲ
AI landing new question type RPA + AI =?
[team learning] [phase 34] Baidu PaddlePaddle AI talent Creation Camp
Dab-detr: dynamic anchor boxes are better queries for Detr translation
Analysis on urban transportation ideas of 2022 Zhongqing cup C
深耕开发者生态,加速AI产业创新发展 英特尔携众多合作伙伴共聚
[ArcGIS tutorial] thematic map production - population density distribution map - population density analysis
接口自动化测试实践指导(中):接口测试场景有哪些
随机推荐
【实践出真理】import和require的引入方式真的和网上说的一样吗
DAB-DETR: DYNAMIC ANCHOR BOXES ARE BETTER QUERIES FOR DETR翻译
Gpt-3 is a peer review online when it has been submitted for its own research
Zhou Yajin, a top safety scholar of Zhejiang University, is a curiosity driven activist
深耕开发者生态,加速AI产业创新发展 英特尔携众多合作伙伴共聚
Implementation of JSTL custom function library
程序员上班摸鱼,这么玩才高端!
B站大佬用我的世界搞出卷积神经网络,LeCun转发!爆肝6个月,播放破百万
Digital chemical plants realize the coexistence of advantages of high quality, low cost and fast efficiency
Wechat can play the trumpet. Pinduoduo was found guilty of infringement. The shipment of byte VR equipment ranks second in the world. Today, more big news is here
Intel David tuhy: the reason for the success of Intel aoten Technology
Network Security Learning - Information Collection
图灵诞辰110周年,智能机器预言成真了吗?
EasyCVR无法使用WebRTC进行播放,该如何解决?
[record of question brushing] 2 Add two numbers
Up to 5million per person per year! Choose people instead of projects, focus on basic scientific research, and scientists dominate the "new cornerstone" funded by Tencent to start the application
高薪程序员&面试题精讲系列120之Redis集群原理你熟悉吗?如何保证Redis的高可用(上)?
jvm是什么?jvm调优有哪些目的?
Win11玩绝地求生(PUBG)崩溃怎么办?Win11玩绝地求生崩溃解决方法
ACL2022 | 分解的元学习小样本命名实体识别