当前位置:网站首页>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 :

  1. char * inputIp
  2. int ip[4];
  3. 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 :

  1. // crt_sscanf_s.c
  2. // This program uses sscanf_s to read data items
  3. // from a string named tokenstring, then displays them.
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. int main( void )
  7. {
  8. char tokenstring[] = “15 12 14…”;
  9. char s[81];
  10. char c;
  11. int i;
  12. float fp;
  13. // Input various data from tokenstring:
  14. // max 80 character string plus NULL terminator
  15. sscanf_s( tokenstring, “%s”, s, _countof(s) );
  16. sscanf_s( tokenstring, “%c”, &c, sizeof(char) );
  17. sscanf_s( tokenstring, “%d”, &i );
  18. sscanf_s( tokenstring, “%f”, &fp );
  19. // Output the data read
  20. printf_s( “String = %s\n”, s );
  21. printf_s( “Character = %c\n”, c );
  22. printf_s( “Integer: = %d\n”, i );
  23. printf_s( “Real: = %f\n”, fp );
  24. }

For the case of reading multiple strings . The code is as follows :

  1. 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

原网站

版权声明
本文为[Full stack programmer webmaster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207062148547301.html

随机推荐