Sscanf and scanf

Source: Internet
Author: User

Sscanf

Name:

Sscanf ()-read data that matches the specified format from a string.

Function prototype:

Int sscanf (string STR, string FMT, mixed var1, mixed var2 ...);

Int scanf (const char * Format [, argument]...);

Note:

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-% sign}

Note:

1. * can also be used in the format. (% * D and % * s) with an asterisk (*) indicates skipping this data and not reading it. (that is, do not read this data into the parameter)

2. {A | B | c} indicates A, B, and C. Select [d], which indicates D or D.

3. width indicates the read width.

4. {H | L | i64 | L}: parameter size. Generally, h indicates a single-byte size, I indicates a 2-byte size, and l indicates a 4-byte size (double exception ), l64 indicates 8-byte size.

5. Type: this is a lot, such as % s and % d.

6. Special: % * [width] [{H | L | i64 | L}] type indicates that values that meet this condition are filtered out and no value is written to the target parameter.

Collection operations are supported:

% [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, greedy

[Edit this section]

1. Common usage.

Char Buf [512] =;

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: There is a space after)

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.

Sscanf is similar to a regular expression, but does not have a strong regular expression. Therefore, we recommend that you use a regular expression for complex string processing.

//-------------------------------------------------------

Sscanf, indicating formatting input from string

In STR, input a number to X, which is 32700.

A long time ago, I thought c didn't have its own split string function. Later I found sscanf. For a long time, I thought sscanf could only define strings with spaces. Now I found that I was wrong.

Sscanf is a runtime function. Its prototype is simple:

Int sscanf (

Const char * buffer,

Const char * Format [,

Argument]...

);

Its powerful functions are reflected in its support for format.

I used to separate a string like this 2006: 03: 18:

Int A, B, C;

Sscanf ("200:0:18", "% d: % d", A, B, C );

And-2006: 04: 18:

Char sztime1 [16] = "", sztime2 [16] = "";

Sscanf ("2006:0:18-2006:04:18", "% s-% s", sztime1, sztime2 );

But later, I needed to handle

The space on both sides of '-' is canceled, but the % s definition of the string is broken.

I need to re-design a function to handle this situation? This is not complicated, but in order to make all the Code have a uniform style, I need to change many places and replace the existing sscanf with my own split function. I thought I must do this and fell asleep with a strong dissatisfaction with sscanf. I woke up and found that I didn't have.

The format-type has a type field such as %. If the string to be read is not separated by spaces, you can use % [].

% [] Is similar to a regular expression. [A-Z] indicates that all characters of A-Z are read, and [^ A-Z] indicates that all characters except a-Z are read.

That's why the problem was solved:

Sscanf ("2006:0:18-2006:04:18", "% [0-9,:]-% [0-9,:]", sztime1, sztime2 );

In softmse (Jake) question post http://community.csdn.net/Expert/topic/4843/4843294.xml? In temp =. 4321558, Zhou Xingxing gave a cool sscanf use case, and then learned how to find that sscanf is awesome.

Original problem:

Iios/12ddwdff @ 122

How to obtain the string between/and @?

Is there any function in the C program?

Zhou xing's code:

# Include <stdio. h>

Int main ()

{

Const char * s = "iios/12ddwdff @ 122 ";

Char Buf [20];

Sscanf (S, "% * [^/]/% [^ @]", Buf );

Printf ("% s/n", Buf );

Return 0;

}

Result: 12 ddwdff.

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.

Function prototype:

Int scanf (const char * Format [, argument]...);

The format can be one or more {% [*] [width] [{H | L | i64 | L}] type | ''| '/T' | '/ n' | non-% sign },

Note: {A | B | c} indicates A, B, and C. Select [d], which indicates D or D.

Width: width, which can be ignored. Its usage is as follows:

Const char sourcestr [] = "Hello, world ";

Char Buf [10] =;

Sscanf (sourcestr, "% 5 s", Buf); // % 5 s, only 5 Characters

Cout <Buf <Endl;

Result: Hello

{H | L | i64 | L}: parameter size. Generally, h indicates the size of a single byte, I indicates the size of 2 bytes, and l indicates the size of 4 bytes (double exception ), l64 indicates 8-byte size.

Type: this is a lot, that is, % s, % d and so on.

Special:

% * [Width] [{H | L | i64 | L}] type indicates that values that meet this condition are filtered out and no value is written to the target parameter. For example:

Const char sourcestr [] = "Hello, world ";

Char Buf [10] =;

Sscanf (sourcestr, "% * S % s", Buf); // % * s indicates that the first matching % s is filtered out, that is, hello is filtered out.

Cout <Buf <Endl;

Result: World

Collection operations are supported:

% [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, greedy

Are you familiar with it? Yes, it's very similar to regular expressions, and it still supports filtering, that is, % * [A-Z]. For example:

A review of the example of star brother:

Const char * s = "iios/12ddwdff @ 122 ";

Char Buf [20];

Sscanf (S, "% * [^/]/% [^ @]", Buf );

Printf ("% s/n", Buf );

Take the string from example 3-to 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

Therefore, the code of Zhou Xing should be summarized:

Const char * s = "iios/12ddwdff @ 122 ";

Char Buf [20];

Sscanf (S, "% * [^/]/% [^ @]", Buf );

Printf ("% s/n", Buf );

First, filter out "iios/", and then a string of 12 ddwdff until the character '@' (in Example 3, you can get this string to @, and remove @ 122). The content is: 12ddwdff is sent to the Buf. The result is displayed.

 

 

Scanf

 

[Edit this section]

Edit this section]

Edit this section]

% A reads a floating point value (valid only for c99)

% A same as above

% C reads one character

% D read a decimal integer

% I reads decimal, octal, and hexadecimal Integers

% O read an octal integer

% X reads hexadecimal Integers

% X same as above

% C reads one character

% S reads a string, ending with spaces, tabs, or line breaks.

% F is used to input real numbers. It can be input in decimal or exponential form.

% F same as above

% E Same as above

% E Same as above

% G same as above

% G same as above

% P reads a pointer

% U reads an unsigned decimal integer

% N number of equivalent characters that have been read to this point

% [] Scan Character Set combination

% Read % symbol

Additional format description: The delimiter table modifier specifies the L/L length modifier input "long" Data

H-length modifier input "short" Data

W integer constant specifies the width of input data

M specifies the width of the input data

* An asterisk is used to read data.

HH, ll, same as H, l, but only valid for c99.

(B) The blank character will slightly remove one or more blank characters in the reading operation of the scanf () function. The blank character can be space, tab, newline, and so on, until the first non-blank character appears. (C) A non-blank character or non-blank character will remove the scanf () function from reading the same character as this non-blank character.

Note: The scanf () control string knowledge is introduced here (it should be relatively complete). If any omission occurs, add it next time. The following describes the use cases of the control strings of the scanf () function. Example 1. # include "stdio. H"

Int main (void)

{

Int A, B, C;

Scanf ("% d", & A, & B, & C );

Printf ("% d, % d, % d/N", a, B, c); Return 0;

} Input three values as follows: 3 □4 □5 (input values of A, B, and C) 3, 4, 5 (A, B, and 5 output by printf, value of C) (1) In & A, & B, and & C, and obtain the memory addresses of these three variables respectively.

(2) "% d" is to input three values in the decimal value format. You can use one or more spaces, Tab keys, and enter keys to separate data.

The following are valid input methods:

① 3 □□□4 □□□5

② 3

4 □5

③ (Tab key) 4

5

Example 2. # include "stdio. H"

Int main (void)

{

Int A, B, C; scanf ("% d, % d, % d", & A, & B, & C );

Printf ("% d, % d, % d/N", a, B, c); Return 0;

} Enter three values as follows: 3, 4, 5 (enter the values of A, B, and C) or 3, □4, □5 (enter a, B, C value) 3, □□□4, □5 (enter the values of A, B, and C)

......

They are all legal, but "," must be followed by a number, for example:

3 □, 4, □5 is invalid and the program fails. (Solution and cause) for example: 1. The address must be used for variables in sacnf. Int A, B;

Scanf ("% d", a, B); // Error

Scanf ("% d", & A, & B); 2. The format control string of scanf () can use other non-blank characters, however, these characters must be entered. Example:

Scanf ("% d, % d", & A, & B );

Input: 3, 4 (the comma corresponds to the comma in "% d, % d)

Scanf ("A = % d, B = % d", & A, & B );

Input: A = 3, B = 4 ("A =", "B =", comma and "A =" in "% d, % d ", "B =" corresponds to a comma)

3. When "% C" is used for input, spaces and escape characters are both valid characters. Example:

Scanf ("% C", & C1, & C2, & C3 );

Input: A □b □c

Result: A → C1, □→ C2, B → C3 (other discarded)

When the scanf () function receives input data, it ends a data input in the following circumstances: (instead of ending the scanf function, the scanf function only has data in each data field and ends after pressing enter ).

① In case of space, "enter", and "Skip" keys.

② End with width.

③ Illegal input. Question 2: Does the scanf () function correctly accept strings with spaces? For example, I love you!

# Include <stdio. h>

Int main ()

{

Char STR [80];

Scanf ("% s", STR );

Printf ("% s", STR); Return 0;

} Input: I live you!

Output: When the I scanf () function receives input data, it ends the input of a data entry in the following circumstances: (instead of ending the scanf function, the scanf function only has data in each data field, and press Enter ).

① In case of space, "enter", and "Skip" keys.

② End with width.

③ Illegal input. Therefore, the above program cannot achieve the expected purpose. scanf () scans the space after "I" and considers the assignment of STR to an end, and ignores the "love you! ". Note that" love you! "It is still in the keyboard buffer zone (I have seen this on the internet, but after debugging, I found that, in fact, the first and last pointers of the buffer string are equal, that is, the buffer zone is cleared, the scanf () function should only scan the stdin stream, and the residual information is in stdin ). Let's change the above program to verify it: # include <stdio. h>

Int main ()

{

Char STR [80];

Char str1 [80];

Char str2 [80];

Scanf ("% s", STR);/* enter: I love you! */

Printf ("% s", STR );

Sleep (5);/* Wait 5 seconds to tell you where the program is running */

Scanf ("% s", str1);/* you do not need to enter the two statements, but scan the keyboard disk buffer */

Scanf ("% s", str2);/* you do not need to enter the two statements, but scan the keyboard disk buffer */

Printf ("/n % s", str1 );

Printf ("/n % s", str2 );

Return 0;

} Input: I love you!

Output: I

Love

You! Okay, the reason is clear. Can the scanf () function complete this task? The answer is yes! Do not forget that the scanf () function has a % [] format controller (if you are not familiar with % [], please refer to the previous article). Please refer to the following program: # include "stdio. h"

Int main ()

{

Char string [50];

/* Scanf ("% s", string); cannot receive space characters */

Scanf ("% [^/n]", string );

Printf ("% s/n", string );

Return 0;

} Question 3: residual information of the Keyboard Buffer

# Include <stdio. h>

Int main ()

{

Int;

Char C; do

{

Scanf ("% d", & );

Scanf ("% C", & C );

Printf ("A = % d c = % C/N", a, c );

/* Printf ("c = % d/N", c );*/

} While (C! = 'N ');

} Scanf ("% C", & C); why cannot this sentence normally receive characters? We use printf ("c = % d/N", c); Use int to represent C and enable printf ("c = % d/N", C ); in this sentence, let's see what the scanf () function assigns to C. The result is c = 10 and the ASCII value is 10? Line feed:/n. by the way, each time we press the "enter" key, we send a "Press ENTER" (/R) and a "line feed" (/N) to the keyboard buffer ), here/R is processed by the scanf () function (think so ^_^), And/N is assigned to C by the scanf () function "incorrectly. solution: Add fflush (stdin) after two scanf () functions, and getch (); getchar () when the statement is added, we will not analyze it here. Let's explore it by yourself. But add fflush (stdin); whatever the situation is feasible. Function Name: fflush

Function: clears a stream.

Usage: int fflush (File * stream); # include <stdio. h>

Int main ()

{

Int;

Char C; do

{

Scanf ("% d", & );

Fflush (stdin );

Scanf ("% C", & C );

Fflush (stdin );

Printf ("A = % d c = % C/N", a, c);} while (C! = 'N ');

} Here is another example that uses a space character to process the residual information in the buffer zone: run the program that has an error: # include <stdio. h>

Int main ()

{

Int I;

Char J;

For (I = 0; I <10; I ++)

{

Scanf ("% C", & J);/* There is no space before % */

}

} After the space control operator is used: # include <stdio. h>

Int main ()

{

Int I;

Char J;

For (I = 0; I <10; I ++)

{

Scanf ("% C", & J);/* Note that there is a space before % */

}

} You can run it to see how different the two programs are. Question 4 how to deal with the program deadlock or error caused by incorrect input of the scanf () function? # Include <stdio. h>

Int main ()

{

Int A, B, C;/* calculate a + B */scanf ("% d, % d", & A, & B );

C = A + B;

Printf ("% d + % d = % d", A, B, C );

} For the above program, if the values of A and B are entered correctly, there is no problem. However, you cannot ensure that the user can enter the correct value every time. Once the wrong type is entered, your program is not a deadlock, but an incorrect result. Haha, maybe everyone has encountered a problem, right? Solution: When the scanf () function is successfully executed, the return value is the number of successfully read variables. That is to say, your scanf () function has several variables. If all the scanf () functions are read normally, it returns a few. But pay attention to another problem. If illegal data is input, there may be residual information in the keyboard buffer. Correct routine: # include <stdio. h>

Int main ()

{

Int A, B, C;/* calculate a + B */while (scanf ("% d, % d", & A, & B )! = 2) fflush (stdin );

C = A + B;

Printf ("% d + % d = % d", A, B, C );

 

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/q3498233/archive/2009/10/05/4633551.aspx

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.