Sscanf function and sscanf function usage
1 // usage example
2 # include <stdio. h>
3 # include <string. h>
4 # define N 512
5 int main ()
6 {
7 char buf [N], buf2 [N], buf3 [N];
8 memset (buf, 0, sizeof (buf ));
9 memset (buf2, 0, sizeof (buf2 ));
10 memset (buf3, 0, sizeof (buf3); // contains the header file string. h
11
12 // 1. Common usage
13 sscanf ("123456", "% s", buf); // here buf is the array name, which means to store 123456 in the form of % s into buf
14 printf ("% s \ n", buf); // The result is: 123456
15
16 // 2. Obtain a string of the specified length. In the following example, a string with a maximum length of 4 bytes is obtained.
17 sscanf ("123456", "% 4 s", buf );
18 printf ("% s \ n", buf); // The result is: 1234
19
20 // 3. Obtain the string of the specified character. For example, in the following example, take a string that encounters any lowercase letter.
21 sscanf ("123456 abcdedf", "% [^ a-z]", buf );
22 printf ("% s \ n", buf); // The result is: 123456
23
24 // 4. Obtain 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.
25 sscanf ("123456 abcdedfBCDEF", "% [1-9a-z]", buf );
26 printf ("% s \ n", buf); // The result is: 123456 abcdedf
27
28 // 5. given a string iios/12DDWDFF @ 122, get the string between/and @, first filter out "iios/", and then send a string other than '@' to the buf.
29 sscanf ("iios/12DDWDFF @ 122", "% * [^/]/% [^ @]", buf );
30 printf ("% s \ n", buf); // The result is 12 DDWDFF.
31
32 // 6. Given a string "hello, world", only world is retained. (Note: "," is followed by a space. % s is stopped when a space is used, and * is added to ignore the first read string)
33 sscanf ("hello, world", "% * s % s", buf );
34 printf ("% s \ n", buf); // The result is: world
35 // % * s indicates that the first matching % s is filtered out, that is, "hello," is filtered out. If there is no space, the result is NULL.
36
37 // 7. The most concise format is the string of the tab Interval
38 sscanf ("string1 \ tstring2 \ tstring3", "% s", buf, buf2, buf3 );
39 printf ("% s \ t % s \ n", buf, buf2, buf3); // The result is: String 1 string 2 string 3
40}
Reference link:
Http://baike.baidu.com/link? Url = required _