[Reserved] SCANF () function Doubt [Author] ------ Knocker

xiaoxiao2021-03-06  14

First, preamble

The scanf () function is the second function encountered during the learning C language (the first function is Printf (), the "Hello, World" program in the C language process (the first function is Printf (), Brian W. Keninghan & Dennis M.Ritchie Basically, all the first example of all C language learners), so the scanf () function should be a function that C learner can be skilled, but there are many beginners can't use this function, in actual programming. Error uses a scanf () function, leading to the program to generate a certain error that cannot be run normally, so that the "scanf () function has bugs", "scanf () function is unused, etc. This article combines the author's problems in programming practice and the forum, but the author is limited (rookie-level), it is inevitable that there is a fallacy, but also hope that one will be directed. (Email: knocker.k@126.com) Only, the next two two articles describe the usage of the scanf () function in the C language, focusing on using common errors and countermeasures that occur during the SCANF () function. Of course, some of the solutions in the text can be better resolved with other functions and methods, but this article only discusses the scanf () function itself. The upper article, the configuration of the SCANF () function control string is described in detail. The next article, introduces the common errors and countermeasures techniques that appear in the SCANF () function control string using the actual routine.

Second, the control string of the scanf () function

Function Name: Scanf Features: Performing Format Input 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. White character; 3. Non-blank characters;

(A) formatting the specifier

Format character description

% A reads a floating point value (only C99 effective)% a to read a character% D read into a decimal integer% i read into decimal, octal, hexadecimal integer% O read into an octal integer% x Into the hexadecimal integer% x to read a character% c to read a string% f Reading a floating point% f The same upper% E, the same maximum, the same maximum, the same, the upper% g, the upper% p, read into a pointer % u Reads an equal value character number% of unsigned decimal integers% N to this read value [] Scan Character Set %% Read% Symbol Additional Format Description Chart

Modification

L / L length modifier input "long" data H length modifier input "Short" data W Integrity Specify input data The width of the input data * the asterisk is empty to read a data HH, LL is the same as above H, L but only is valid 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 (the value of the A, B, and C output by 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 button) 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 ↙ (input A, B, C) ... all 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); input: 3, 4 ↙ (comma) SCANF ("A =% D, b =% D) ", & A, & b); input: a = 3, b = 4 ↙ (" a = "," b = ", comma and"% D,% D "" a = "," b = "and comma Correspondingly) 3, when entering "% C", spaces and "escape characters" are active as a valid character.

Example: Scanf ("% C% C% C", & C1, & C2, & C3); input: a □ b □ C↙ Result: A → C1, □ → C2, B → C3 (the rest of the lost)

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.

The last article wrote here, the third section of the routine "copy" from a tutorial from the Internet (the reasons are two: One, you can play a lot less words. Second, □ I don't know how to play. ^ _ ^) And delete the mistakes. This is also a word, readers here: Everything has to be pro, even if it is a classic book, it is not exempt from omissivity, so the compiler is the most reliable, it is It is wrong to tell you if the compiler will tell you.

I have expressed two views here, and I reiterated this time: 1. This article only discusses the Scanf () function control string, all routines of this article do not constitute program suggestions. 2. Everything has to be pro, different compilers of different platforms may have different results. All routines in this article are debugged under Win-TC Windows Me.

Fourth, SCANF () function control string common error and countermeasure skills

Question 1: The program is compiled, but the error prompts are as follows: scanf: floating point formats not linked Abnormal Program Termination

Error sample program:

#include int main (void) {Int i, j; float s [3] [3]; / * Here * / for (i = 0; i <3; i ) for (j = 0; J <3; J ) Scanf ("% F", & S [i] [j]);

For (i = 0; i <3; i ) for (j = 0; j <3; j ) Printf ("% f", s [i] [j]);}

This is actually a problem that is not related to the topic of this article, but also is not related to the scanf () function, is a compiler.

The reason is clear: no link floating point library. Early system memory resources are tight, and the amount of multi-dimensional floating point array takes up the amount of memory (one-dimensional floating point array does not have this problem), so TC is trying to do not add a unrelated part when compiling. When not found a floating point conversion program, it is not This section is installed in the executable program. Sometimes TC does not correctly identify that it is actually really a floating point conversion, so it will appear above. Solved method: Tell TC to do input conversion of floating point numbers. Add the following statement to the above program. There is / * here * /

Method 1: Float C; scanf ("% f", & c);

Method 2: Float C, * T; // This handle error, now correct & t === "* T;

T = & C; .....

That is, the compiler only has a floating point conversion, and TC will connect floating point conversion, so there is a floating point variable in general a larger program. But the problem is not over. I have a "one-dimensional floating point array without this question", then let's take a look at this way:

#include int main (void) {Int i, j; float s [3] [3], * PTR; PTR = & S [0] [0]; for (i = 0; i <3; i ) for (j = 0; j <3; j ) scanf ("% f", PTR i * 3 j);

For (i = 0; i <3; i ) for (j = 0; j <3; j ) Printf ("% 7.2f / n", s [i] [j]);}

This way we drop the multi-dimensional floating point array to a one-dimensional floating point array to process, debug it, and the program runs normally. This shows that the TC compiler only has this "unlink floating point library" in the process of processing the multi-dimensional float array (structure).

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: i

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.

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 how to run to where * / scanf ("% s", str1); / * These two do not need you Reputable, is the reproduction of the keyboard buffer again * / scanf ("% s", str2); / * This two sentences do not need you to enter, is the re-scanning of the keyboard buffer * / printf ("/ n% s ", str1); Printf (" / n% s ", str2); return 0;} input: 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); no spaces * / 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 handled out (just think so, ^ _ ^), and / N is assigned to C by the scanf () function "error".

Solution: You can add fflush (stdin) after two scanf () functions; there is also getCH (); getchar (); can also, but to be placed as a specific scanf () statement plus that, this is not analyzed here. Readers to explore themselves. But add fflush (stdin); no matter what situation is feasible.

Function Name: FFLUSH Function: Clear a flow: int 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 this * / }

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 this * /}}

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; / * calculates 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.

The correct routine:

#include int main () {Int a, b, c; / * calculates A B * /

While (Scanf ("% D,% D", & A, & B)! = 2) fflush (stdin); c = a b; Printf ("% D % D =% D", A, B, C); }

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

New Post(0)