sscanf,sscanf_s and its related use methods

Source: Internet
Author: User
Tags uppercase letter

#include <stdio.h>

Defines the function int sscanf (const char *str,const char * format,........);

Function description
SSCANF () Converts and formats the data in the string based on the parameter format string. Format conversion form please refer to scanf ().

The converted result is stored in the corresponding number of parameters.

The return value succeeds returns the number of parameters, and the failure returns 1, and the reason for the error is stored in errno. return 0 indicates failure or otherwise. Indicates the number of correctly formatted data such as: sscanf (str.    "%d%d%s", &i,&i2, &s);    Assume that three becomes both read-in success will return 3. Suppose that just reading the first integer to I returns 1. proves that the second integer cannot be read from Str.

Main ()
{
int i;
unsigned int J;
Char input[]= "Ten 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);
}

Run AAAAA

As we all know, sscanf is a very useful function that allows you to take integers, floating-point numbers, strings, and so forth from a string. It is simple to use, especially for integers and floating-point numbers. But newbies may not know some of the high-level uses of working with strings. Let's make a brief description here.

1. Common use methods.

CHARSTR[512]={0};
SSCANF ("123456", "%s", str);
printf ("str=%s", str);

2. Take a string of the specified length. As in the following example, take a string with a maximum length of 4 bytes.

SSCANF ("123456", "%4s", str);
printf ("str=%s", str);

3. The string to take to the specified character. As in the following example. String that encounters a space.

SSCANF ("123456abcdedf", "%[^]", str);
printf ("str=%s", str);

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

SSCANF ("123456abcdedfBCDEF", "%[1-9a-z]", str);
printf ("str=%s", str);

5. The string to be taken to the specified character set. As in the following example. String that encounters an uppercase letter.

SSCANF ("123456abcdedfBCDEF", "%[^a-z]", str);
printf ("str=%s", str);

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

You can convert an IP address in the form of a string to four integers with the following code, for example:

    1. Char * Inputip
    2. int  Ip[4];
    3. sscanf_s (Inputip, "%d.%d.%d.%d", &ip[0], &ip[1],&ip[2],&ip[3]);

Pay attention to sscanf_s. When the type being read into is an integer or other length that can be determined by the type. You cannot keep up with the length behind the type, but for the length of the string type (char *) You must clearly indicate the maximum length of the string (that is, the space that can be accommodated) after the type. The proportions are as follows:

  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. int Main ( void )
  8. {
  9. Char tokenstring[] = "..."  ;
  10. Char  s[81];
  11. Char  C;
  12. int  i;
  13. float  FP;
  14. //Input various data from tokenstring:   
  15. //Max 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. }

For multiple string read-in scenarios. 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 function is very useful, unexpectedly I have never known this function. Recent friends use VS2008 to knock code with the security version number of this function sscanf_s. There is an abnormal problem. Unable to parse the string without saying, it will crash.

int sscanf_s (
const char *buffer,
const char *format [,
argument ] ...
);

This is the MSDN definition of the function, without continuing to look at the subsequent notes, as well as instances of the case. The difference between sscanf and sscanf_s is not felt at all. Thought it was still used like sscanf. So that strange problems arose.

Example:
crt_sscanf_s.c//This program uses sscanf_s to read the data items//from a string named tokenstring and then displays them. #i Nclude <stdio.h> #include <stdlib.h>int main (void) {   char  tokenstring[] = "...";   Char  s[81];   Char  C;   int   i;   float FP;   Input various data from tokenstring:   //MAX 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 the entire document, see this instance, only to find that there is still a trick! sscanf_s when the value is taken. You need to specify the maximum size of the value after each value.

When compiling a program with VS2005, there is a lot of warning that the function being used is unsafe. The version number of "_s" should be added with the security version number, which is the function name.

Warning Content:
warning C4996: ' sscanf ': This function or variable could be unsafe. Consider using sscanf_s instead.

It is understood that the "_s" version number function is Microsoft later on C + + to expand. Used to replace a previously unsafe function. For example: printf, scanf, strcpy, fopen and so on.

Specific references:
Ms-help://ms. Vscc.v80/ms. Msdn.v80/ms. Visualstudio.v80.chs/dv_vccrt/html/d9568b08-9514-49cd-b3dc-2454ded195a3.htm

The function of the original security version number, check the parameters and buffer bounds, add the return value and throw the exception. This adds the security of the function, reducing the chance of error.
At the same time this also means when using these functions. Sometimes you have to enter a lot of other parameters about the size of the buffer, you can hit a few more keyboards to get less trouble. Worth!

The following summarizes the SSCANF's and sscanf_s's regular usage, as well as the special meaning of the "_s" version number 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,the use of sscanf. take the parse time string as an example. Resolves the string "2009-01-02_11:12:13" to integer-month-day seconds

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

(1) must be in strict accordance with the delimiter form to fill in, if you encounter a mismatch will terminate the resolution


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 completed according to the form of cutting symbols, the number of characters must be consistent. such as being able to 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 completed according to the form of cutting symbols, the number of characters must be consistent. Ditto,%1s can be equated 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 completed according to the form and quantity of cutting characters, the type must be consistent. such as being able to correctly parse "2009/01/02___11:12:13"
The sscanf is used here, similar to the generic regular representation but not all the same,%*c means ignoring consecutive characters


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, the use of sscanf_s

Defined
Char cc[2];
TM tm_temp={0};
String Stime ("2009-01-02_11:12:13");

(1) Same as sscanf the first method, can 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) When parsing data using the%c format. You must add a length parameter to the corresponding buffer. Otherwise there will be an error


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) When parsing data using the%s format. Buffer length must be greater than string length, otherwise not resolved


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) Same as SSCANF, sscanf_s supports the same form


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 control sscanf and the use of sscanf_s, can see the latter to buffer security has a lot of other considerations, so as to avoid a lot of casual trouble.

As we all know, sscanf is a very useful function that allows you to take integers, floating-point numbers, strings, and so forth from a string.

It's easy to use. Especially for integers and floating-point numbers. But newbies may not know some of the high-level uses of string handling, so here's a quick explanation.

1. Common use methods.

Here is the reference fragment:
char str[512] =;
SSCANF ("123456", "%s", str);
printf ("Str=%sn", str);

2. Take a string of the specified length. As in the following example, take a string with a maximum length of 4 bytes.

Here is the reference fragment:
SSCANF ("123456", "%4s", str);
printf ("Str=%sn", str);

3. The string to take to the specified character. As in the following example. String that encounters a space.

Here is the reference fragment:
SSCANF ("123456 Abcdedf", "%[^]", str);
printf ("Str=%sn", str);

4. Take a string that includes only the specified character set. As in the following example. A string containing only 1 to 9 and lowercase letters.

Here is the reference fragment:
SSCANF ("123456abcdedfBCDEF", "%[1-9a-z]", str);
printf ("Str=%sn", str);

5. The string to be taken to the specified character set.

As in the following example, take a string that encounters an uppercase letter.

here is the reference fragment:
SSCANF ("123456abcdedfBCDEF", "%[^a-z]", str);
printf ("Str=%sn", str);

sscanf,sscanf_s and its related use methods

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.