Sscanf, sscanf_s and related usage

Source: Internet
Author: User

# Include <stdio. h>

Define the function int sscanf (const char * STR, const char * format ,........);

Function Description
Sscanf () converts and formats the STR string based on the format string. For more information about format conversion, see scanf (). The converted result is stored in the corresponding parameter.

If the return value is successful, the number of parameters is returned. If the return value fails,-1 is returned. The error cause is stored in errno. If the return value is 0, the operation fails. Otherwise, the number of correctly formatted data is displayed, for example, sscanf (STR, "% d % s", & I, & I2, & S ); if the three data entries are successfully read, 3 is returned. If the first integer is read-only to I, 1 is returned. The second integer cannot be read from Str.

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 % s", I, j, S );
}

Run 10 27 aaaaa

As we all know, sscanf is a very useful function that can be used to retrieve integers, floating-point numbers, and strings from strings. It is easy to use, especially for integers and floating-point numbers. However, beginners may not know some advanced usage when processing strings. Here is a brief description.

1. Common usage.

Charstr [512] = {0 };
Sscanf ("123456", "% s", STR );
Printf ("str = % s", STR );

2. Take a string of the specified length. In the following example, a string with a maximum length of 4 bytes is obtained.

Sscanf ("123456", "% 4 s", STR );
Printf ("str = % s", STR );

3. Obtain the string of the specified character. For example, in the following example, the string is obtained when a space is encountered.

Sscanf ("123456 abcdedf", "% [^]", STR );
Printf ("str = % s", STR );

4. Take a string that only contains the specified character set. For example, in the following example, take a string that only contains 1 to 9 letters and lowercase letters.

Sscanf ("123456 abcdedfbcdef", "% [1-9a-z]", STR );
Printf ("str = % s", STR );

5. Obtain the string of the specified character set. For example, in the following example, a string with uppercase letters is used.

Sscanf ("123456 abcdedfbcdef", "% [^A-Z]", STR );
Printf ("str = % s", STR );

//////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /////////////

You can use the followingCodeConvert an IP address in string format to four integers:

    1. Char* Inputip
    2. IntIP Address [4];
    3. Sscanf_s (inputip,"% D. % d", & IP [0], & IP [1], & IP [2], & IP [3]);

Note: sscanf_s: When the read type is an integer or another type with a certain length, it cannot keep up with the length after the type, but for the string type (char *) if the length is unknown, you must specify the maximum length (that is, the space that can be accommodated) of the string after the type ). Example:

  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.   
  5. # Include <stdio. h>
  6. # Include <stdlib. h>
  7. IntMain (Void)
  8. {
  9. CharTokenstring [] ="15 12 14 ...";
  10. CharS [81];
  11. CharC;
  12. IntI;
  13. FloatFP;
  14. // Input various data from tokenstring:
  15. // Max 80 character string plus null Terminator
  16. Sscanf_s (tokenstring,"% S", S, _ countof (s ));
  17. Sscanf_s (tokenstring,"% C", & C,Sizeof(Char));
  18. Sscanf_s (tokenstring,"% D", & I );
  19. Sscanf_s (tokenstring,"% F", & FP );
  20. // Output the data read
  21. Printf_s ("String = % s \ n", S );
  22. Printf_s ("Character = % C \ n", C );
  23. Printf_s ("INTEGER: = % d \ n", I );
  24. Printf_s ("Real: = % F \ n", FP );
  25. }

The code for reading multiple strings is as follows:

    1. Sscanf_s (inputstring,"% S. % s", S1, s1.length, S2, s2.length, S3, s3.length, S4, s4.length );

The sscanf function is very useful, but I never knew it before. Recently, my friend wrote it in vs2008.ProgramWhen this function is used in the secure version sscanf_s, there is an exception, the string cannot be parsed, it will crash.

Int sscanf_s (
Const char *Buffer,
Const char *Format[,
Argument]...
);

This is the definition of the function in msdn. If you do not continue to view the following remarks and the instance details. I cannot see the difference between sscanf and sscanf_s. I thought it was still used like sscanf, resulting in a strange problem.

 
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 );}
 
It wasn't until you read the entire document and saw this instance that it was tricky! When setting the sscanf_s value, you must specify the maximum value after each value.

When using vs2005 to compile a program, a lot of warnings are reported, saying that the function used is insecure. You should use a secure version, that is, add the "_ s" version to the function name.
 
Warning content:
 Warning c4996: 'sscanf': This function or variable may be unsafe. Consider using sscanf_s instead.
 
It is understood that the "_ s" version function was extended by Microsoft to C ++ to replace previously insecure functions, such as printf, scanf, strcpy, and fopen.

For details, refer:
MS-help: // Ms. VSCC. v80/ms. msdn. v80/ms. visualstudio. v80.chs/dv_vccrt/html/d9568b08-9514-49cd-b3dc-2454ded195a3.htm

In the original security version, the function checks the parameters and buffer boundaries, adds the return value and throws an exception. This increases the Function Security and reduces the chance of errors.
At the same time, this also means that when using these functions, sometimes you have to enter more parameters about the buffer size. typing a few more keyboards can be less troublesome and worth it!

The following summarizes the common sscanf and sscanf_s methods, and also reflects the special features of the "_ s" version function and the original function:

1. The difference between sscanf and scanf is the input source. The former is a string, and the latter is a standard input device.

2,Use of sscanf,The following example uses the time string to parse the string ": 12: 13" into an integer year, month, day, hour, minute, and second.

// Define
Char cc;
TM tm_temp = {0 };
String stime ("2009-01-02_11: 12: 13 ");

// (1) the domain name must be matched in the form of a separator. If no match exists, the resolution is 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) it may not be entered in the form of separated symbols, and the number of characters must be consistent. For example, you can correctly parse "2009/01/02 _ 11:12:13"

 

Sscanf (stime. c_str (), "% 4D % C % 2D % C % 2D % C % 2D % C % 2D % 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) it may not be entered in the form of separated symbols, and the number of characters must be the same. Same as above, % 1 s can be equivalent to % C

 
Sscanf (stime. c_str (), "% 4D % 1 S % 2D % 1 S % 2D % 1 S % 2D % 1 S % 2D % 1 S % 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) the type must be the same as that of the separator. For example, you can correctly parse "2009/01/02 ___ 11:12:13"
// The sscanf regular expression is used here. It is similar to a common regular expression but not exactly the same. % * C indicates that multiple 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. Use sscanf_s

// Define
Char CC [2];
TM tm_temp = {0 };
String stime ("2009-01-02_11: 12: 13 ");

// (1) the first method of sscanf is the same. You can use the format "% 4D-% 2D-% 2D _ % 2D: % 2D: % 2D: % 2D" for 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) when parsing data in the % C format, the length parameter must be added to the corresponding buffer; otherwise, an error will occur.

Sscanf_s (stime. c_str (), "% 4D % C % 2D % C % 2D % C % 2D % C % 2D % 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) when parsing data in % s format, the buffer length must be greater than the string length; otherwise, the data will not be parsed.

Sscanf_s (stime. c_str (), "% 4D % 1 S % 2D % 1 S % 2D % 1 S % 2D % 1 S % 1 S % 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) Like sscanf, sscanf_s also supports regular expressions

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
);

By comparing the use of sscanf and sscanf_s, we can see that the latter has more considerations for buffer security, thus avoiding a lot of casual troubles.

As we all know, sscanf is a very useful function that can be used to retrieve integers, floating-point numbers, and strings from strings. It is easy to use, especially for integers and floating-point numbers. But novice users can
I don't know some advanced usage when processing strings. Here is a brief description.

1. Common usage.

The following is a reference clip:
Char STR [512] =;
Sscanf ("123456", "% s", STR );
Printf ("str = % Sn", STR );

2. Take a string of the specified length. In the following example, a string with a maximum length of 4 bytes is obtained.

The following is a reference clip:
Sscanf ("123456", "% 4 s", STR );
Printf ("str = % Sn", STR );

3. Obtain the string of the specified character. For example, in the following example, the string is obtained when a space is encountered.

The following is a reference clip:
Sscanf ("123456 abcdedf", "% [^]", STR );
Printf ("str = % Sn", STR );

4. Take a string that only contains the specified character set. For example, in the following example, take a string that only contains 1 to 9 letters and lowercase letters.

The following is a reference clip:
Sscanf ("123456 abcdedfbcdef", "% [1-9a-z]", STR );
Printf ("str = % Sn", STR );

5. Obtain the string of the specified character set. For example, in the following example, a string with uppercase letters is used.

The following is a reference clip:
Sscanf ("123456 abcdedfbcdef", "% [^A-Z]", STR );
Printf ("str = % Sn", STR );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.