当前位置:网站首页>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
边栏推荐
- Ssm+jsp realizes the warehouse management system, and the interface is called an elegant interface
- [system management] clear the icon cache of deleted programs in the taskbar
- 测试/开发程序员怎么升职?从无到有,从薄变厚.......
- The root file system of buildreoot prompts "depmod:applt not found"
- POJ training plan 2253_ Frogger (shortest /floyd)
- [OA] excel document generator: openpyxl module
- 用CPU方案打破内存墙?学PayPal堆傲腾扩容量,漏查欺诈交易量可降至1/30
- SSM+jsp实现仓库管理系统,界面那叫一个优雅
- Fix the problem that the highlight effect of the main menu disappears when the easycvr Video Square is clicked and played
- 科兴与香港大学临床试验中心研究团队和香港港怡医院合作,在中国香港启动奥密克戎特异性灭活疫苗加强剂临床试验
猜你喜欢
MySQL forgot how to change the password
Continuous learning of Robotics (Automation) - 2022-
Digital chemical plant management system based on Virtual Simulation Technology
Food Chem | in depth learning accurately predicts food categories and nutritional components based on ingredient statements
Easycvr cannot be played using webrtc. How to solve it?
Kivy tutorial of setting the size and background of the form (tutorial includes source code)
测试/开发程序员怎么升职?从无到有,从薄变厚.......
图灵诞辰110周年,智能机器预言成真了吗?
【ArcGIS教程】专题图制作-人口密度分布图——人口密度分析
The easycvr platform is connected to the RTMP protocol, and the interface call prompts how to solve the error of obtaining video recording?
随机推荐
sscanf,sscanf_s及其相关使用方法「建议收藏」
EasyCVR平台接入RTMP协议,接口调用提示获取录像错误该如何解决?
How do test / development programmers get promoted? From nothing, from thin to thick
Lecture 3 of "prime mover x cloud native positive sounding, cost reduction and efficiency enhancement lecture" - kubernetes cluster utilization improvement practice
leetcode 53. Maximum subarray maximum subarray sum (medium)
2022 electrician cup question B analysis of emergency materials distribution under 5g network environment
Intel and Xinbu technology jointly build a machine vision development kit to jointly promote the transformation of industrial intelligence
【实践出真理】import和require的引入方式真的和网上说的一样吗
In cooperation with the research team of the clinical trial center of the University of Hong Kong and Hong Kong Gangyi hospital, Kexing launched the clinical trial of Omicron specific inactivated vacc
Fix the problem that the highlight effect of the main menu disappears when the easycvr Video Square is clicked and played
掌握软件安全测试方法秘笈,安全测试报告信手捏来
Poor math students who once dropped out of school won the fields award this year
图灵诞辰110周年,智能机器预言成真了吗?
MySQL null value processing and value replacement
Pyqt5 out of focus monitoring no operation timer
EasyCVR无法使用WebRTC进行播放,该如何解决?
kivy教程之设置窗体大小和背景(教程含源码)
SSM+JSP实现企业管理系统(OA管理系统源码+数据库+文档+PPT)
leetcode 53. Maximum Subarray 最大子数组和(中等)
Highly paid programmers & interview questions. Are you familiar with the redis cluster principle of series 120? How to ensure the high availability of redis (Part 1)?