当前位置:网站首页>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
边栏推荐
- 科兴与香港大学临床试验中心研究团队和香港港怡医院合作,在中国香港启动奥密克戎特异性灭活疫苗加强剂临床试验
- 2022 electrician cup a question high proportion wind power system energy storage operation and configuration analysis ideas
- 每人每年最高500万经费!选人不选项目,专注基础科研,科学家主导腾讯出资的「新基石」启动申报
- EasyCVR无法使用WebRTC进行播放,该如何解决?
- B站大佬用我的世界搞出卷积神经网络,LeCun转发!爆肝6个月,播放破百万
- Win11控制面板快捷键 Win11打开控制面板的多种方法
- Video fusion cloud platform easycvr video Plaza left column list style optimization
- kivy教程之设置窗体大小和背景(教程含源码)
- NFT meta universe chain diversified ecosystem development case
- Web3 社区中使用的术语
猜你喜欢
C#使用西门子S7 协议读写PLC DB块
What about the collapse of win11 playing pubg? Solution to win11 Jedi survival crash
见到小叶栀子
[team learning] [phase 34] Baidu PaddlePaddle AI talent Creation Camp
How do test / development programmers get promoted? From nothing, from thin to thick
Mongo shell, the most complete mongodb in history
mpf2_线性规划_CAPM_sharpe_Arbitrage Pricin_Inversion Gauss Jordan_Statsmodel_Pulp_pLU_Cholesky_QR_Jacobi
【实践出真理】import和require的引入方式真的和网上说的一样吗
EasyCVR平台接入RTMP协议,接口调用提示获取录像错误该如何解决?
This "advanced" technology design 15 years ago makes CPU shine in AI reasoning
随机推荐
Digital chemical plants realize the coexistence of advantages of high quality, low cost and fast efficiency
[team learning] [34 issues] scratch (Level 2)
抖音或将推出独立种草社区平台:会不会成为第二个小红书
Win11控制面板快捷键 Win11打开控制面板的多种方法
高薪程序员&面试题精讲系列120之Redis集群原理你熟悉吗?如何保证Redis的高可用(上)?
What is CGI, IIS, and VPS "suggested collection"
Why does WordPress open so slowly?
Mongo shell, the most complete mongodb in history
数学分析_笔记_第10章:含参变量积分
一度辍学的数学差生,获得今年菲尔兹奖
True global ventures' newly established $146million follow-up fund was closed, of which the general partner subscribed $62million to invest in Web3 winners in the later stage
B站大佬用我的世界搞出卷积神经网络,LeCun转发!爆肝6个月,播放破百万
How to conduct website testing of software testing? Test strategy let's go!
The most complete deployment of mongodb in history
C#使用西门子S7 协议读写PLC DB块
Case reward: Intel brings many partners to promote the innovation and development of multi domain AI industry
【实践出真理】import和require的引入方式真的和网上说的一样吗
[team learning] [phase 34] Baidu PaddlePaddle AI talent Creation Camp
Easycvr cannot be played using webrtc. How to solve it?
Analysis on urban transportation ideas of 2022 Zhongqing cup C