Sscanf_ powerful data Read-transform

Source: Internet
Author: User
Tags uppercase letter

function<cstdio>sscanfintSSCANF (Const Char* S,Const Char*format, ...); Read formatted Data from stringReads Data fromS and stores them according to parameter format into the locations given by the additional arguments, as ifSCANF was used, but reading froms instead of the standard input (stdin). The additional arguments should point to already allocated objects of the type specified by their corresponding format SPE Cifier within the formatstring. PARAMETERSSCstringthat the function processes asIts source to retrieve the DATA.FORMATCstringthat contains a formatstringThat follows the same specifications asFormatinchscanf (see scanf fordetails) .... (Additional arguments) Depending on the formatstring, the function may expect a sequence of additional arguments, each containing a pointer to allocated storagewhereThe interpretation of the extracted characters isstored with the appropriate type. There should is at least asMany of these arguments asThe number of values stored by the format specifiers. Additional arguments is ignored by the function. Return ValueOn Success, the function returns the number of itemsinchThe argument list successfully filled. This count can match the expected number of items or is less (even zero)inchThe Caseof a matching failure. in the Caseof an input failure before any data could be successfully interpreted, EOF isReturned.
function prototypes: int sscanf (const char *, const char *, ...); int sscanf (const char *buffer,const char *format,[argument] ...); The data stored in buffer is formatted with the format Control string argument the selective setting string sscanf reads data from buffer and writes the data to the argument according to format. Header file #include <stdio.h> or #include <cstdio>return value Success returns the number of arguments, failure returns-1, the cause of the error is stored in errno. After several tests [source request], in the Linux systemThe successful return is the number of successfully converted values, for example: sscanf ("1 2 3", "%d%d%d", BUF1, Buf2, BUF3); A successful call returns a value of 3, which means that the BUF1,BUF2,BUF3 is successfully converted. SSCANF ("1 2", "%d%d%d", BUF1, Buf2, BUF3); A successful call returns a value of 2, which is the only buf1,buf2 successful conversion. (Note: Here buf are addresses) sscanf is similar to scanf, which is used for input, except that the latter takes the keyboard (stdin) as the input source, the former with a fixed string as the input source.

A format control, similar to a regular expression:

the second parameter of sscanf can be one or more {%[*] [width] [{h | I | I64 | L}]type | ' | ' \ t ' | ' \ n ' | Non-% symbol} Note: 1, * can also be used in the format, (that is,%*d and%*s) with an asterisk (*) indicates that skipping this data is not read in. (that is, do not read this data into the parameters) 2. {A|b|c} indicates that a a,b,c is selected, [d], indicating that either D or D may not be available. 3. Width indicates read widths. 4. {h | l | I64 | L}: The size of the parameter, usually h represents a single-byte size,i that represents a 4-byte size (double exception) for a 2-byte size,l, and L64 represents a 8-byte size. 5, type: This is a lot of, is%s,%d and so on. 6. Special:%*[width] [{h | l | I64 | L}]type indicates that the condition is filtered out and no value is written to the target parameter Failure returns 0, otherwise the number of formatted parameters is returnedSupport set operation%[a-z] means match any character in a to Z, greed (as many matches as possible)%[ab '] matches a, B, ' one member, greedy%[^a] matches any character not a, and stops reading, greedy example 1. Common usage.
123 charbuf[512];sscanf("123456","%s",buf);//此处buf是数组名,它的意思是将123456以%s的形式存入buf中!printf("%s\n",buf);
The result is: 1234562. Takes a string of the specified length. As in the following example, take a string with a maximum length of 4 bytes.
12 sscanf("123456","%4s",buf);printf("%s\n",buf);
The result is: 12343. The string to take to the specified character. As in the following example, take a string that encounters any lowercase letter.
12 sscanf("123456abcdedf","%[^a-z]",buf);printf("%s\n",buf);
The result is: 1234564. Takes a string that contains only the specified character set. As in the following example, take a string that contains only 1 to 9 and lowercase letters.
12 sscanf("123456abcdedfBCDEF","%[1-9a-z]",buf);printf("%s\n",buf);
The result is: 123456ABCDEDF when input: sscanf ("123456abcdedfBCDEF", "%[1-9a-z]", buf);
1 printf("%s\n",buf);
The result: 123456BCDEF (wrong!!) Note: The result should be: 123456 "If you encounter a character that is not a 1-9 or a-Z, you will end up with" 5 "when you encounter a lowercase letter. The string to be taken to the specified character set. As in the following example, take a string that encounters an uppercase letter.
12 sscanf("123456abcdedfBCDEF","%[^A-Z]",buf);printf("%s\n",buf);
The result is: 123456abcdedf6, given a string iios/[email protected], gets/And the string between @, first filter out "iios/", and then send a string of non-' @ ' to BUF
12 sscanf("iios/[email protected]","%*[^/]/%[^@]",buf);printf("%s\n",buf);
The result is: 12ddwdff7, given a string "Hello, World", preserving only the world. (Note: "," followed by a space,%s with a space stop, plus * is to ignore the first read to the string)
12 sscanf(“hello, world”,"%*s%s",buf);printf("%s\n",buf);
The result is: World%*s indicates that the first match to the%s was filtered out, i.e. "Hello," is filtered if there are no spaces then the result is null. 8, the most concise format is the string of the tab interval
12 sscanf(“字符串1\t字符串2\t字符串3”,"%s%s%s",str1,str2,str3);printf("%s\t%s\t%s\n",str1,str2,str3);
The result is: String 1 string 2 string 3

SSCANF and sscanf_s Common methods, the original security version of the function, the parameters and buffer bounds are checked, added the return value and throw an exception. This increases the security of the function and reduces the chance of error.
This also means that when you use these functions, sometimes you have to enter more parameters about the size of the buffer, more than a few keystrokes can be replaced by less trouble, it is worth!

The following summarizes the common methods of sscanf and sscanf_s, as well as the special functions 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, the latter is the standard input device

2,the use of sscanf, in order to parse the time string as an example, the string "2009-01-02_11:12:13" resolved to Integer date and time seconds

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

(1) must be in strict accordance with the form of a delimiter to fill in, if encountering a mismatch, terminate the parsing

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 the symbol, the number of characters must be consistent, for example, 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 completed according to the form of the symbol, the number of characters must be consistent, ibid,%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 in accordance with the form and number of separators, type must be consistent, for example, can correctly parse "2009/01/02___11:12:13"
A regular expression of sscanf is used here, similar but not identical to a generic regular representation, and%*c means 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, the use of sscanf_s

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

(1) The same as the first method of sscanf, you can use the "%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, the length parameter must be added to the corresponding buffer, or an error will occur

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, the buffer length must be greater than the string length, otherwise it will not parse

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) 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 on buffer security, thus avoiding many casual troubles.

As we all know, sscanf is a useful function to take out integers, floating-point numbers, and strings 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 string handling, so here's a quick explanation.

    stringTimein ="2016-09-17 09:48:13.560"; TM Tm_timein= {0 }; intTimeoutmsectemp =0; sscanf_s (Timein.c_str (),"%4d-%2d-%2d%2d:%2d:%2d.%3d",        &Tm_timein.tm_year,&Tm_timein.tm_mon,&Tm_timein.tm_mday,&Tm_timein.tm_hour,&Tm_timein.tm_min,&Tm_timein.tm_sec,&timeinmsectemp); Tm_timein.tm_year-=1900;//year, which refers to the difference from 1900Tm_timein.tm_mon-=1;//month, 0 stands for January, so subtract 1Chardt[ -];ctime_s (DT,sizeofdt,&time_t_in); cout<< DT << Endl;//Sat Sep 09:48:13 2016\nCharbat[ -];asctime_s (Bat,sizeofBAT, &Tm_timein); cout<< bat << Endl;

Sscanf_ powerful data Read-transform

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.