Use of sscanf and sprintf Input and Output in C language and explanations of Strlen and Memset

Source: Internet
Author: User

Use of sscanf and sprintf Input and Output in C language and explanations of Strlen and Memset
Sscanf ()-read data that matches the specified format from a string. Swscanf ()-This function is used to process wide character strings. It is similar to sscanf. By learning and using this function, I personally think that the string format is not very complex, but it is not easy to use this function, this scale depends on your own. The string is not very complex, but writing a processing function is troublesome and inefficient. You can use this function. If the string is very complex, use a regular expression.
Let's talk about it more. Let's take a look at the following introductions and columns! Name: sscanf ()-read data that matches the specified format from a string.
Function prototype:
Int sscanf (string str, string format, mixed var1, mixed var2 ...);
Int scanf (const char * format [, argument]...); Description:
Similar to scanf, sscanf is used for input, but the latter uses the screen (stdin) as the input source, and the former uses a fixed string as the input source.
The format can be one or more {% [*] [width] [{h | l | I64 | L}] type | ''| '\ T' | '\ n '| non-% symbol} supports the set operation:
% [A-z] indicates matching any character in a to z, greedy (as many as possible)
% [AB '] matches a, B, and', greedy
% [^ A] matches any character other than a. Examples of greed: 1. Common usage. Char buf [512] = {0 };
Sscanf ("123456", "% s", buf );
Printf ("% s \ n", buf );
Result: 123456
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", buf );
Printf ("% s \ n", buf );
Result: 1234
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", "% [^]", buf );
Printf ("% s \ n", buf );
Result: 123456

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]", buf );
Printf ("% s \ n", buf );
Result: 123456 abcdedf

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]", buf );
Printf ("% s \ n", buf );
Result: 123456 abcdedf
6. Given a string iios/12DDWDFF @ 122, get the string between/and @ and filter out "iios/" first, then, send a string of content other than '@' to the buf.
Sscanf ("iios/12DDWDFF @ 122", "% * [^/]/% [^ @]", buf );
Printf ("% s \ n", buf );
Result: 12 DDWDFF.

7. Given a string "hello, world", only world is retained. (Note: "," followed by a space) sscanf ("hello, world", "% * s % s", buf); printf ("% s \ n ", buf );
Result: world
% * 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.
8. char * s = "1try234delete5"
Sscanf (s, "1% [^ 2] 234% [^ 5]", s1, s2 );
The non-converted characters (before % or after conversion) in the format of scanf, that is, 1234 in this example is used to skip the corresponding characters in the input;
The meanings of '[]' are the same as those in regular expressions, indicating matching the character sequence in the regular expression; ^ indicates the opposite. When using [], the input variables must be arrays of char, signed char, and unsigned char with sufficient storage space. Remember [It is also a conversion character, so there is no s.
8. Split the string marked with a certain character. Char test [] = "222,333,444, 555,666 ";
Char s1 [4], s2 [4], s3 [4], s4 [4], s5 [4], s6 [4], s7 [4];
Sscanf (test, "% [^,], % [^,], % [^,], % [^,], % [^,], % [^,], % [^,] ", s1, s2, s3, s4, s5, s6, s7 );
Printf ("sssa1 = % s", s1 );
Printf ("sssa2 = % s", s2 );
Printf ("sssa3 = % s", s3 );
Printf ("sssa4 = % s", s4 );
Printf ("sssa5 = % s", s5 );
Printf ("sssa6 = % s", s6 );
Printf ("sssa7 = % s", s7 );
9. An example of extracting mail addresses from users' personal data

# Include
 
  
# Include
  
   
Using namespace std; int main () {char a [20] = {0}; char B [20] = {0}; // assume that the email address is '; 'End sscanf ("email: jimmywhr@gmail.com;", "% * [^:]: % [^;]", ); // assume that the email address does not have a specific ending sign sscanf ("email: jimmywhr@gmail.com", "% * [^:]: % s", B ); printf ("% s \ n", a); printf ("% s \ n", B); system ("pause"); return 0 ;}
  
 

The key is "% * [^:]: % [^;]" and "% * [^:]: % s ".
% * [^:] Indicates that the conditions in "[]" are filtered out and no value is written to the target parameter. In this example
The first ':' character will be filtered out during writing. '^' indicates a negative meaning. The entire parameter Translation
In plain text, all (not ':') characters before the first ':' are filtered out.
: Skip.
% [^;] Copy characters until ';' is encountered ';'. From: http://blog.csdn.net/lbird/archive/2007/08/03/1724429.aspx
% [] Usage: % [] indicates that a character set is to be read. If [followed by the first character is "^", it indicates the inverse meaning. The string in [] can be 1 or more characters. The null character set (% []) violates regulations and can lead to unpredictable results. % [^] Is also in violation of regulations.
% [A-z] reads the string between a-z. If it is not earlier than this, it is stopped, for example, char s [] = "hello, my friend"; // Note :, comma between non-a-z sscanf (s, "% [a-z]", string); // string = hello
% [^ A-z] reads strings not between a-z. If a character between a-z is encountered, it is stopped, for example, char s [] = "HELLOkitty "; // note: the comma is sscanf (s, "% [^ a-z]", string) between not a-z; // string = HELLO
% * [^ =] The variable is not saved with the * sign. Skips a qualified string. Char s [] = "notepad = 1.0.0.1001"; char szfilename [32] = ""; int I = sscanf (s, "% * [^ =]", szfilename ); // szfilename = NULL, because int I = sscanf (s, "% * [^ =] = % s", szfilename) is not saved ); // szfilename = 1.0.0.1001% 40c 40 characters
% [^ =] Reads the string until the '=' sign is reached. '^' can be followed by more characters, such as: char s [] = "notepad = 1.0.0.1001 "; char szfilename [32] = ""; int I = sscanf (s, "% [^ =]", szfilename); // szfilename = notepad if the parameter format is: % [^ =:], you can also read notepad from notepad: 1.0.0.1001. Example: char s [] = "notepad = 1.0.0.1001"; char szname [32] = ""; char szver [32] = ""; sscanf (s, "% [^ =] = % s", szname, szver); // szname = notepad, szver = 1.0.0.1001 summary: % [] has many functions, but it is not very common, mainly because: 1. Scanf functions of multiple systems have vulnerabilities. (In typical cases, TC sometimes fails when entering the floating point type ). 2. Complicated usage and error-prone. 3. It is difficult for the compiler to perform syntax analysis, thus affecting the quality and execution efficiency of the target code. I personally think that 3rd is the most critical, and the more complicated the functions, the lower the execution efficiency. Some simple string analysis can be processed by ourselves.
Sprintf () string formatting command
The main function is to write formatted data into a string. Sprintf is a variable parameter function.

Sprintf

Function declaration: int sprintf (char * buffer, const char * format [, argument1, argument2,…])

Purpose: write a piece of data into the string buffer starting with the address buffer.

Library file:

Parameter: (1) buffer, the starting address of the data to be written; (2) format, the format of the data to be written; (3) argument: The data to be written, which can be in any format.

Return Value: the actual length of the Written string.

Note: This function requires the buffer overflow to keep enough length for the argument to be written. It can be used to replace itoa, that is, to convert integers into strings.

Snprintf

Function declaration: int snprintf (char * str, size_t size, const char * format ,...)

Purpose: Security Mode of sprintf. The parameter size is greater than that of sprintf. Write a piece of data into the string buffer starting with str. The maximum length of a string cannot exceed the length size. If the value exceeds or equal to, only size-1 is written, followed by '\ 0 '.

Library file:

Parameter: (1) str, the start address of the data to be written; (2) size, maximum length of the data to be written (the actual write must be less than or equal to this value, including '\ 0 '); (3) format: format of the data to be written; (4) argument (ellipsis): Data to be written

For example:

The result is

It should be noted that the returned value of snprintf is the length of the string after format, and is not the length of the string buffer actually copied.


How to Use strlen, a common function in C Language

Function declaration: extern unsigned int strlen (char * s );

Function library: <喎?"http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + kernel/nWuLXE19a3 + kernel + CrLOyv2junPOqtfWt/u0rrXEs/XKvLXY1rc8L3A + kernel/kernel + cjxwifsawdupq = "left">

Compile the running result

Note:

The strlen function is easy to understand, and its functions and sizeof functions are easy to confuse. Sizeof refers to the Memory Length occupied after the string is declared. It is an operator, not a function. strlen is a function, which starts from the first byte and counts backwards, it stops until '\ 0' is met.

How to Use memset, a common function in C Language

Function declaration: void * memset (void * s, int ch, size_t n );

Purpose: assign the value represented by ch to each byte of a piece of memory. The value is ASCII encoded.

Function library: Or

Parameters: (1) s, start memory address; (2) ch and n, starting from address s, within the next n bytes length, assign the value of each byte to n.

Example:

The Code is as follows:

Compile the running result

Note:

The most common purpose of this function is to initialize a new allocated memory to 0. For example, line 9-10 of our code.

Note that the value of the second parameter of the function represents the value of each byte to be set. Therefore, be careful when the second parameter is not 0. For example, line 12-13 of our code. IntArray [0] is a four-byte integer. Each byte of intArray will be 1. After running row 12th, the content of intArray [0] is as follows:

(Binary) 00000001 00000001 00000001 00000001 = (decimal) 16843009

This is why the output result of the 13th row is 16843009.





Related Article

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.