For many reasons, when I first started learning programming, I didn't learn the C language. I learned the object-oriented C ++ directly. But now, in many environments, it is found that C is also a good language. It is particularly effective to use C to solve the problem. Like its most basic scanf () function, I think it is amazing. (So I am studying hard .) The scanf () function is the second function that all C language learners encounter when learning C language (the first function is printf (), Brian W. kerninghan & Dennis M. ritchie's "Hello, world" program is basically the first example for all C language learners. Therefore, scanf () functions should be a function that C learners can skillfully use, however, many beginners cannot use this function very well. In actual programming, the scanf () function is incorrectly used, leading to errors that may occur in the program and failing to run properly, resulting in "scanf () function Bug, scanf () function useless theory, and so on.
In this article, I will explain the problems that I encountered in programming practices and on the Forum. However, the level of my skills is limited (cainiao-level). It is inevitable that there are errors. I also hope that I can give some advice. (Email: knocker.k@126.com)
This article introduces the usage of the scanf () function in C language, and focuses on Common Errors and countermeasures during the use of the scanf () function. Of course, some solutions in this article can be better solved by using other functions and methods, but this article only discusses scanf () function itself.
The first part describes in detail the composition of the scanf () function control string. Next, we will introduce common errors and Countermeasures in the use of scanf () function control strings using actual routines. Ii. scanf () function control string function name: scanf
Function: format the input.
Usage: int scanf (char * Format [, argument,...]); the scanf () function is a common terminal formatting input function that reads input information from the standard input device (keyboard. You can read any inherent type of data and automatically convert the value into an appropriate internal format. The call format is scanf ("<formatted string>", <Address Table>). The scanf () function returns the number of successfully assigned data items. If an error occurs, EOF is returned. Its Control string consists of three types of characters: 1. Format the specifier;
2. Blank space character;
3. Non-blank characters;
(A) Format the specifier
Format character description % A reads a floating point value (only c99 valid)
% 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
% F reads a floating point number
% 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
* 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.
Write it here in the previous article. The routine in the third section "copy" a tutorial from the Internet (for two reasons: 1. You can play less words. 2. □i don't know how to fight. ^_^), And delete the errors. here, I would also like to remind the readers of this article that everything should be done by yourself. Even classic books have some omissions. Therefore, it is the most reliable to use compilers to speak, yes. If yes, please let the compiler tell you.
I have already expressed two points in the previous article. I would like to reiterate here: 1. This article only discusses the use of scanf () function control strings. All routines in this Article do not constitute programming suggestions. 2. Everything must be done by yourself. Different compilers on different platforms may have different results. All routines in this article are debugged in WIN-TC + Windows ME. 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 );
}
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.