C language scanf function detailed explanation

xiaoxiao2021-03-06  55

Function name: scanf

Function: Implementation formatting

Usage: int Scanf (char * format [, argument, ...]);

The scanf () function is a universal terminal formatting input function, which is read from the standard input device (keyboard). You can read any natural type data and automatically convert the numerical value into an appropriate machine format.

Its call format is: scanf ("",

);

The scanf () function returns the number of data items that successfully assigned values, and EOF is returned when an error.

Its control string consists of three types of characters:

1. Format specifier;

2. Blank character;

3. Non-blank characters;

(A) formatting the specifier

Format character description

% A reads a floating point value (only C99 is valid)

% A

% C reads a character

% D read into a decimal integer

% i read in decimal, octal, hexadecimal integer

% O reads an eight-input integer

% x read into hexadecimal integers

% X

% C reads a character

% s reads a string

% f Reads a floating point number

% F

% e

% E

% g

% G

% P read into a pointer

% u read into an unsigned decimal integer

The number of equivalent characters of% N to this read value

% [] Scan Character Collection

%% read% symbol

Additional format description character table

Modification

L / L length modifier input "long" data

H length modifier input "short" data

W Integrity Specifies the width of the input data

* Asterisk empty reading a data

HH, LL is the same as above H, L but is only effective for C99.

(B) blank characters

Blank characters will make the scanf () function to one or more blank characters in the input in the read operation, and the blank character can be Space, Tab, Newline, and the like until the first non-empty composite appears.

(C) Non-blank characters

A non-empty character will cause the scanf () function to remove the same character as this non-blank character.

Note: SCANF () control string knowledge will introduce here (it should be completely ^ _ ^), if there is any missing next time. Next, the actual routine will be set forth one by one.

Third, the use of the SCANF () function control string

example 1.

#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 ↙ (inputs A, B, C)

3, 4, 5 (Value of the A, B, C) (Value of Printf) (1) & A, & B, & C & C is the address operator, and the memory address of these three variables is obtained separately.

(2) "% D% D% D" is to enter three values ​​in the decay format. When entering, one or more spaces, tab keys, and auto keys can be separated by one or more spaces.

The following is a legal input method:

1 3 □ □ 4 □□□□ 5 ↙

2 3 ↙

4 □ 5 ↙

3 3 (Tab) 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 ↙ (inputs A, B, C)

or

3, □ 4, □ 5 ↙ (inputs A, B, C)

3, □□□ 4, □ 5 ↙ (inputs A, B, C)

......

It is legal, but "," must follow the numbers, such as:

3 □, 4, □ 5 ↙ 非 非 非 非, the program is wrong. (Solution and reason later)

Rethlean:

1, the variables in SACNF () must use the address.

INT A, B;

Scanf ("% D% D", A, B); // error

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

2, SCANF () format control strings can use other non-empty characters, but these characters must be entered when entering.

example:

Scanf ("% D,% D", & A, & b);

Enter: 3, 4 ↙ (comma) Correspondence in "% D,% D")

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

Enter: a = 3, b = 4 ↙ ("a =", "b =", comma "a =", "b =" and comma correspondence in "% D,% D")

3. When entering "% C", spaces and "escape characters" are active as a valid character.

example:

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

Enter: a □ b □ c↙

RESULTS: A → C1, □ → C2, B → C3 (The rest is discarded)

When the scanf () function receives input data, the following is the next input: (not ending the scanf function, the scanf function has data only in each data field, and pressing the Enter).

1 encounter, "Enter", "Jumping" button.

2 The end of the width.

3 illegally input.

Question 2: SCANF () function does not accept a string with spaces? Such as: i love you!

#include

int main ()

{

Char Str [80];

Scanf ("% s", STR);

Printf ("% s", str);

Return 0;

}

Enter: i live you!

Output: The iScanf () function receives input data, and the following is the input of a data: (not ending the scanf function, the scanf function has data only in each data field, and pressing the Enter).

1 encounter, "Enter", "Jumping" button.

2 The end of the width.

3 illegally input.

Therefore, the above procedure does not meet the expected purpose, and the space behind the scanf () scanned to "i" is considered to end the assignment of the STR and ignores the "love you!" Here. Here, pay attention is "Love you!" Keyboard buffer (on this problem, I have seen online, but I have been debugging, in fact, the buffer string first pointer is equal, that is, the buffer is emptied, SCANF () function Should just scan the stdin stream, which is in stdin). We change the above program to verify:

#include

int main ()

{

Char Str [80];

CHAR STR1 [80];

CHAR STR2 [80];

Scanf ("% s", str); / * Enter: i love you! * /

Printf ("% s", str);

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

Scanf ("% s", str1); / * These two sentences do not need you to enter, is the re-scan of the keyboard buffer * /

Scanf ("% s", str2); / * These two sentences do not need you to enter, is a re-scan of keyboard buffers * /

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

Printf ("/ N% S", STR2);

Return 0;

}

Enter: i love you!

Output: i

Love

You!

Ok, the reason is known, can the scanf () function can't complete this task? The answer is: can! Don't forget that the scanf () function has a% [] format control (if you don't know if you don't know about this article), please see the following procedure:

#include "stdio.h"

int main ()

{

CHAR STRING [50];

/ * scanf ("% s", string); can not receive space characters * /

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

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

Return 0;

}

Question 3: Keyboard buffer residual information problem

#include

int main ()

{

Int a;

Char C;

DO

{

Scanf ("% d", & a);

Scanf ("% C", & C);

Printf ("A =% D C =% C / N", A, C);

/ * Printf ("C =% D / N", C); * /

} while (c! = 'n');

}

Scanf ("% c", & c); this sentence does not receive characters normally, what is the reason? We use Printf ("C =% D / N", C); expand C with Int, enable Printf ("C =% D / N", C); this sentence, see the scanf () function assignment to C What is it, the result is c = 10, what is the ASCII value of 10? Retained / n. Right, each of us hit the "Enter" button, send it to the keyboard buffer (/ r), a "wrap" (/ n), here / R is Scranf ( The function is processed (just think so, ^ _ ^), and / n is assigned to c. Solution "error" by the scanf () function: You can add a fflush (stdin) after two scanf () functions , There is also getch (); getChar (); it is also, but it is not analyzed by the specific scanf () statement, and the reader is going to explore it. But add fflush (stdin); no matter what situation is feasible.

Function name: fflush

Function: Clear a stream

Usage: int fflush (file * stream);

#include

int main ()

{

Int a;

Char C;

DO

{

Scanf ("% d", & a);

Fflush (stdin);

Scanf ("% C", & C);

Fflush (stdin);

Printf ("A =% D C =% C / N", A, C);

} while (c! = 'n');

}

Here, give an example of processing buffer residual information with "Space]:

Run an error program:

#include

int main ()

{

INT I;

Char J;

For (i = 0; i <10; i )

{

Scanf ("% c", & j); / * There is no space before% * /

}

}

After using the space control:

#include

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 what you do in seeing two programs.

Question 4 How to deal with the scanf () function error input causes the program deadlock or error?

#include

int main ()

{

INT A, B, C; / * Calculate A B * /

Scanf ("% D,% D", & A, & b);

C = a b;

Printf ("% D % D =% D", A, B, C);

}

If the program is correct, if you correctly enter the value of A and B, then there is no problem, however, you can't guarantee that the user can enter correctly, once you entered the type of error, your program is not a dead lock, just get a wrong result Oh, this may have problems with everyone?

Workaround: The return value when the scanf () function performs success is the number of variables successfully read, that is, your scanf () function has several variables, if the scanf () function is all normal, it returns a few . But here should also pay attention to another problem. If illegal data is entered, the keyboard buffer may also have a residual information issue.

Right routine: #include

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); }

Scanf function discusses 1. Blank comparative problem #include main () {int A; printf ("Input the data / n"); scanf ("% d / n", & a); // Here more A Enter / N Printf ("% D", A); RETURN 0;} The result is to enter two digital programs to end, not one expected. Why? Cause: When the blank end is finished, Scanf will skip the blank character to read a character, so you have to enter a number. The blank characters here include spaces, tabs, wraps, carriage return, and change. So if you use Scanf ("% D", & A), the same problem will also occur. Workaround: This error is not careful when entering it, pay more attention to it. This problem is not good to check, there is no problem with compilation, and a space is not easy to see. When your program appears above, you can check it out. 2. Buffer problem This is a very easy place, I miss many times. #include main () {int N = 5; char C [n]; for (int i = 0; i main () {char C [5]; gets (c); printf (c); return 0;}, but pay attention: This function is automatically Convert your last ring to the carriageway into characters '/ 0'. If your input exceeds the size of the array, it will generate an error. 3. Scanf () function parameter input type does not match Question This is the problem I saw on the 9CBS forum. This error sometimes makes people inexplicably.

#include main () {int a = 123; char C = 't'; Printf ("INPUT / N"); Scanf ("% D% C", & A, & C); scanf ("% D% C ", & A, & C); Scanf ("% D% C ", & A, & C); Printf ("% D / N% C / N ", A, C); RETURN 0;} When input A back After the car, you will directly skip the following two scanf statements, directly output to 123 T, for Scanf ("% D% C", & A, & C), the scanf statement is executed, first try to read a% in the buffer D type data, if the first parameter matches, continue to read data from the buffer and the second parameter, in turn, until all the parameters are matched; if there is a parameter does not match, then Jump from this place, ignore all the parameters behind this scanf, and perform the next statement. You can verify it with the following program: #include int main () {int a = 123, b = 1; char c = 't'; scanf ("% D% D", & A, & B); Scanf ("% C", & C); Printf ("% D / N% D / N% C / N", A, B, C); RETURN 0;} Enter: 2 Enter a Car car resultout: 2 1 a A Solution: The return value of the scanf () function is successful is a number of variables successfully read, that is, you have several variables, if the scanf () function is read normally, it Return a few. But here should also pay attention to another problem. If illegal data is entered, the keyboard buffer may also have a residual information problem. For example: #include main () {Int a = 123, b; while ("% D% D", & A, & B)! = 2) fflush (stdin); printf ("% D / N% D / N ", A, B); RETURN 0;} You can try it, if the input is not a number, there is any reaction. Supplement: A very few of Scanf, but very useful conversion characters: [...] and [^ ...]. #include main () {char strings [100]; scanf ("% [1234567890]", strings); Printf ("% s", strings); return 0;} Run, enter: 1234WEREW, The result is: 1234. It can be found by running that it is: If the input character belongs to a character in the string of square brackets, then the character is extracted; if it is discovered to end the extraction. This method will automatically add a string end to the end of the already extracted characters.

Scanf ("% [^ 1234567890]", strings); its role is: End the extraction if a character is found in the string in square brackets, then end the extraction; if it is not subsequent, the character is extracted. This method will automatically add a string end to the end of the already extracted characters. Note: Side sides cannot be spaced on both sides, such as scanf ("% [1234567890], strings); scanf ("% [^ 1234567890] ", strings); do not allow spaces to count. This method can also solve the problem that there is no space in the input of scanf. Just use scanf ("% [^ / n]", strings); Very magical. Scanf prototype: See "C language Daquan" and K & C # include ; int Scanf () is a universal subroutine read from the standard input stream stdin, You can read all intrinsic types of data and automatically convert into aircraft.

In C99, Format is modified with restrictt. Format is constructed by the above three types of characters: ● Format specifier ● Whitbert ● Non-blank converted characters (just back part) a read floating point value (C99 only) A readout value (only Suitable for C99) C read single character D reading ten into the integer i read 10 yuan, octal, hexadecimal integer E read floating point number E read floating point number F read floating point number F read floating point number (only for C99) G Reading Point Number O Reading Octa-Biography S Read Strings X Read Hexadecimal Number X Reading Hexuo PE Pointer Value N The number of other value characters of the read-entered value U read unsigned decimal integers [] Scan characters Collecting% read% symbol (percent), for example,:% S represents a read string and% D represents a read integer. The processing order of the format string is from left to right, the format specifier matches the change in the change in the variable form. To read long integers, L (ELL) can be placed in front of the format specifier; in order to read the short integer, H can be placed in front of the format specifier. These modifiers can be used with D, I, O, U and X format code. By default, A, F, E, and G tell SCANF () to allocate data for Float. If L (ELL) is placed in front of these modifiers, scanf () assigns data for Double. Using L is telling scanf (), the variable that receives data is a long Double type variable. If the modern compiler program is used to support the increased wide character characteristics in 1995, you can use the C format code, use the Wide character pointer of the type WCHAR_T with the WCHAR_T; can also be used with the S format code, use L modifier description The pointer of the string. l The modifier can also be used to modify the scan set to illustrate the wide character. The blank character in the control string allows scanf () skips one or more blank lines in the input stream. The blank character can be a space (Space), Tab and newline. In essence, the blank character in the control string allows scanf () to read in the input stream, but does not save the result until it is unique. Non-blank characters make Scanf () read a matching character in the stream and ignore it. For example, "% D,% D" enables scanf () to read an integer, and give up the comma in the read, then read another integer. If no match is found, scanf () returns. The variable pool used to save read values ​​in Scanf () must be a variable pointer, that is, the address of the corresponding variable. In the input stream, the data item must be split by spaces, tabs, and new line. Comma and semicolon, etc. are not separators, such as the following code: Scanf ("% D% D", & R, & C); will accept input 10 20, but encounter 10, 20 failed. The asterisk (*) between the percentage (%) and the formatter represents the data read the specified type but does not save. Therefore, scanf ("% D% * C% D", & X, & Y); 10/20 read operation, 10 placed in the variable x, 20 placed in Y. The format command can illustrate the maximum domain width. The integer between the percentage (%) and the format code is used to limit the maximum number of characters read from the corresponding domain. For example, when it is not more than 20 characters to address, it is possible to write into the following form: scanf ("% 20s", address; if the content of the input stream is more than 20 characters, next Scanf () from this time Start reading at the stop.

If you have encountered a blank in front of the maximum domain wide, the reading of this domain stops; at this time, scanf () jumps to the next domain. Although spaces, tabors, and new rows are used as domain segmentation symbols, but read single-character operations are processed in general characters. For example, the input stream "x y" calls: scanf ("% C% C% C", & A, & B, & C); returns, X, the space is in the variable B, Y is in the variable C. Note that other characters in the control string include spaces, tabs, and new lines, are used to match and abandon characters from the input stream, and the matched characters are given up. For example, given input stream "10T20", call: scanf ("% DT% D", & x, & y); put 10 and 20, respectively, T is abandoned, because T is in the control string. The ANSI C standard adds a new feature to scanf (), called scanset. The scan set defines a set of characters that can be read into the characters in which the characters in which the characters are allowed and assigned to the corresponding character array. The scan collection is defined by a string character in a pair of brackets, and the left brackets must be prefixed with a percent sign. For example, the following scan set allows scanf () reads characters a, b, b, b, b, and c:% [ABC], SCANF () continuously ejects characters in the collection and puts the corresponding character array until it is not found. The characters in the characters (ie, scanning only the matching characters). When returned, the array is placed in NULL, and the string consisting of read characters. Use characters ^ to explain. When the character is placed in the first character of the scan set, the complement set of the command consisting of other characters, indicating that scanf () only accepts other characters that are not illustrated. For many implementations, a range can be explained with a hyphen. For example, the following scan set allows scanf () to accept letters A to z:% [A-Z], pay attention to the scan set is case sensitive. Therefore, it is desirable to scan large and lowercase characters, it should be explained separately, lowercase letters, respectively. Scanf () returns the value equal to the domain of successful assignments, but because the unexpred domain is not calculated due to an asterisk modifier. Returns EOF when assigning the first domain. C99 adds several format modifiers for scanf (): HH, LL, J, Z and T. HH modifiers can be used for D, I, O, U, X, X or N. It illustrates the corresponding variable element is a signed or unsigned char value, or when N, the corresponding variable element is a pointer to the LONG CHAR type variable. The LL modifier can also be used for D, I, O, U, X, X or N. It illustrates the corresponding variable elements as a Signed or UNSIGNED long long int value. The J format modifier is applied to D, I, O, U, X, X or N, indicating that the matching of the match is type INTMAX_T or UINTMAX_T. These types are declared in ; and explain the integer of the maximum width. The Z format modifier is applied to D, I, O, U, X, X or N, indicating that the matching variable element is a pointer to the SIZE_T type object. This type is declared in ; and explains the structure of SIZEOF. The T format modifier is applied to D, I, O, U, X, X or N, indicating that the matching variable element is a pointer to the PTRDIFF_T type object. This type is declared in ; and illustrates the difference between the two pointers.

转载请注明原文地址:https://www.9cbs.com/read-93972.html

New Post(0)