Dark Horse programmer--c The--SCANF function of Language Foundation

Source: Internet
Author: User

------- iOS Training look forward to communicating with you! ----------

When we write the code, we can see that almost every C program will include the input and output. The input and output is one of the most basic operations in the program. The C language itself does not provide input and output statements, and the input and output operations are implemented by functions in the C standard function library. Let's talk about it today. Input: scanf function.

The scanf function, like the printf function, is not a C keyword, but simply the name of the library, which is defined in stdio.h, so add #include<stdio.h> when using the scanf function. It is the format input function, that is, in the user-specified format from the keyboard to input data into the specified variable, the keyword at the bottom of the letter F is the meaning of "format".

General form of the scanf function: scanf (format control, Address table column) int scanf (char *format[,argument,...]);

"Format Control" is a string enclosed in double quotation marks, called a "conversion control string", or "format string", which contains two information:

(1), format declaration: composed of% and format characters, the function is to convert the input data into a specified format after input, always by the% character start;

(2), ordinary characters: that is, the characters that need to be entered as they are output.

An Address table column is a table column that consists of several addresses, either the address of a variable or the first address or expression of a string.

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

/* Example: Use the SCANF function to enter data */#include <stdio.h> void Main () {int a,b,c;  printf ("Input a,b,c/n");  scanf ("%d%d%d", &a,&b,&c); printf ("a=%d,b=%d,c=%d", A,b,c);}
    • Format character description

%a,%a read in a floating-point value (valid only C99)

%c reads in one character

%d read-in decimal integer

%i read in decimal, octal, hexadecimal integer

%o Read in octal integer

%x,%x read in hexadecimal integer

%s reads a string, ending with a space, tab, or line break

%f,%f,%e,%e,%g,%g is used to enter real numbers, which can be entered in decimal or exponential form.

%p read in a pointer

%u read in an unsigned decimal integer

%n the equivalent number of characters that have been read into the value

%[] Scan Character Set

Percent Read% sign

Description of additional format specifier character form modifiers

l/l length modifier Enter "Long" data

H-Length modifier input "short" data

W integer constant Specifies the width of the input data

* Indicates that this entry is not assigned to the corresponding variable after it is read into

    • return value of scanf

The return value of the scanf is determined by the following parameters

scanf ("%d%d", &a, &b);

(1) If both A and B are read successfully, then the return value of scanf is 2.

(2) If only A is read in successfully, the return value is 1

(3) If both A and B are not successfully read, the return value is 0

(4) If an error is encountered or an end of file is encountered, the return value is EOF, and the return value is of type int.

    • Issues to be aware of when using the SCANF function

(1) The variable in SACNF () must use the address
(2) The format control string for scanf () can use other non-whitespace characters, but must be entered as input
(3) When input with "%c", the Space and "escape character" are both valid characters

Let's give an example of the specific use of the scanf function and some of the problems encountered during use:

/* Problem One: the scanf () function does not correctly accept strings with spaces?  such as: I love you!*/#include <stdio.h>int main () {char str[80];  scanf ("%s", str);   printf ("%s", str); return 0;}

The scanf () function ends a data input when it receives input data: (not to end the scanf function, the scanf function only has data in each data field and ends with a carriage return).
(1) In case of space, "enter", "Jump" key

(2) Meet the width of the end

(3) Illegal input

Therefore, the above procedure does not achieve the intended purpose, scanf () scan to "I" after the space is considered to end the assignment of STR, and ignore the following "Love you!". Here's the "Love you!" note. Also in the keyboard buffer (on this issue, I see the online statement is so, but I after debugging found that in fact, the buffer string pointer is already equal, that is, the buffer is emptied, the scanf () function should only scan stdin stream, the remaining information is in stdin). Let's change the procedure above to verify:

#include <stdio.h>int main () {char str[80];  Char str1[80];  Char str2[80]; scanf ("%s", str);/* Enter here: I Love you!  */printf ("%s", str); Sleep (5);/* Wait here for 5 seconds to tell you where the program is running */scanf ("%s", str1);/* These two sentences do not need you to enter, is the keyboard disk buffer re-scan */scanf ("%s", str2); * * These two sentences do not need to be entered,  is the keyboard disk buffer re-scan */printf ("/n%s", str1);  printf ("/n%s", str2); return 0;}

Span style= "font-family: ' The song body '; font-size:16px;" > The result is:
I
love you!

Now that the reason knows, then the scanf () function can not complete this task? The answer is: Can! Don't forget that the scanf () function also has a%[] format control (if you don't know about%[), please see the following program:

#include "stdio.h" int main () {char string[50];/*scanf ("%s", string), cannot receive whitespace */scanf ("%[^/n]", string);  printf ("%s/n", string); return 0;}

The program is now in line with the correct output I love you! Now!

/* Problem two: Keyboard buffer residual information problem */#include <stdio.h>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 normally receive characters, what is the reason? We use printf ("c=%d/n", c), c with int, enable printf ("c=%d/n", c), this sentence, see what the scanf () function assigns to C, and the result is c=10, what is the ASCII value of 10? Line break is/N. By the way, we hit the "Enter" key, send a "carriage return" (/R) to the keyboard buffer, a "newline" (/N), where the/R is scanf () function (see ^_^), and/n is scanf () function "Error" to the C. Solution: You can add a fflush (stdin) after the two scanf () function, and add getch (), GetChar () can also, but depending on the specific scanf () statement plus that, here is not analyzed, the reader himself to explore it. But add fflush (stdin); no matter what the situation is.

#include <stdio.h>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's an example of using "whitespace" to handle buffer remnants: The program that runs the 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 using the space control:

#include <stdio.h>int main () {int i;  Char J; for (i = 0;i < 10;i++) {scanf ("%c", &j);/* Note there is a space in front of */}}

Can run to see what is the difference between two programs Oh ~ ~

/* Problem three: How to handle the scanf () function wrong input causes program deadlock or error?  */#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);}

If the above program, if the correct input a, B value, then there is no problem, but you can not guarantee that the user can enter the correct every time, once the wrong type of input, your program is not a deadlock, is to get a wrong result, hehe, this may all have encountered problems it? Workaround: scanf () The return value of the successful execution of the function is the number of variables successfully read, that is, you scanf () function has a few variables, if the scanf () function is all read normally, it returns a few. But there is another problem here, if you enter illegal data, the keyboard buffer may have a residual information problem. The correct routines:

#include <stdio.h>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);}

Add: Fflush (stdin) This method is not available under GCC. (available under VC6.0), the following is the definition of the Fflush function C99:

int fflush (FILE *stream);

if the stream points to an output stream or update stream (update stream), and the update streamThe most recent operation is not an input, then the Fflush function writes any data that is not written to the streama file (such as a standard output file, stdout) that points to. Otherwise, the behavior of the Fflush function is indeterminate. fflush (NULL) empties all output streams and the update streams mentioned above. If a write error occurs, FflushThe function will mark those streams with an error and return EOF, otherwise 0 is returned. It follows that if the stream points to an input stream (such as stdin), then the behavior of the Fflush function is indeterminate. Therefore usefflush (stdin) is not correct, at least the transplant is not good. You can use the following methods:

/* This function can be used with the scanf function, but be aware when using%c input that this function can only be used in cases where the buffer is not empty */void flush () {char C;  while ((C=getchar ())! = '/n ' &&c!=eof);  } #include <stdio.h> int main () {int a,b,c;/* Calculates a+b*/while (scanf ("%d,%d", &a,&b)!=2) flush ();  C=a+b; printf ("%d+%d=%d", A,b,c);}

Dark Horse programmer--c The--SCANF function of Language Foundation

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.