C in scanf () function usage

Source: Internet
Author: User
Tags character set mixed modifier stdin valid

I think, in the input and output function, the scanf () function, it should be the most troublesome, sometimes it gives us the result is ridiculous, but must be a reason ....

First of all, this log is not an article that describes the usage of various format characters in scanf () (It is not necessary, but you must use it).

I tried a lot of input, including some wrong exercises, once to scanf () from the confusion to awake, and again from the awake to confusion ... Do not know when is an end, who let C so advanced?

Posted here, but also want to let themselves occasionally can see, also want to know whether their understanding is wrong, where the fault (so I have a thick skin, put on it).

Note that the keyboard buffers are closely related to the input, and that type matching is also extremely important for input!!

Enter the following topics:

The operation of the scanf convection conforms to the type-matching operation principle, and if the type does not match, it will not read the input stream. So the input stream will be stuck, and if the input stream is not empty, scanf will not wait for user input and enter directly from the buffer.
But how does scanf () match? What is stdin again?
The search on the internet on the match is very little, some of the reasons for the details can not be found.
So, I took the liberty to come to the conclusion that:
Example: scanf ("%d,%d", &i,&j); Input: 12, 13 return the car however, j!=13. Note that after 12 there is a space, why?
Reason: I explained that in scanf (), the normal characters in the format string (excluding white space characters) are strictly matched, because%d of the format strings is followed by a ', ', so the number 12 in the input must be a ', '.

scanf ("1123%s", &str); Input: STR is aaabb at 1123aaabb, however, when entering 24AABBDD, an error occurs because 1123 must be strictly matched.

In addition: scanf ("%d/n", &i);      printf ("i=%d", I); How do I enter it to output: i=12? It's not what you think it is, there's a chance to try it!
Some examples:
SCANF () is a function with a return value, what is its return value? How do you take advantage of this feature?
scanf () in the matching principle: in this 5th specific description ...
scanf () the start condition in which the various data formats match, and the end condition.
Such as:%d,/n, etc. type Enter the end condition.

scanf ("%d/n", &i);p rintf ("%d", I); Input 12 return car, and no output, why?
The end condition of the scanf () function: The function ends when the individual format matches are complete and there is a carriage return at the end.
scanf ("%s", str) cannot continue entering 127 consecutive entries. TC, VC seems to be more than 4,000.

Description The keyboard buffer length is one byte? But the stdin->bsize (buffer size) is actually 512, and why?
stdin data residue in buffer: scanf ("%3s", str);  C= GetChar ();  Input: AAABBCCC Enter, at this time str= "AAA", c= ' B '; Data residue in buffer!
Getch () does not pass through the buffer, directly receives the characters entered on the keyboard.
In the example above, add a ch=getch (); But Getch () does not read any of the BBCCC, stating that Getch () is not the same as GetChar () and that they read the values differently for enter!
An infrequently used format:%[], such as scanf ("%[a-z]", str);

Input: Abcdefdsaabcdef output: str= "ABCDEFDSA";
How do I use scanf () to enter a string with a space?
When scanf () is processed, a enter is sent to the buffer with two values: a carriage return (10), a newline (13). You can use GetChar () to receive (but only if/n, or 13) is received.
After a scanf () function, add a fflush (stdin) to clear the input data residue?
scanf ("%3s", str); Fflush (stdin); C=getchar ();

Direct Input AAABBBDDD carriage return, C can also get value?
Here is a detailed explanation:
The return value when the scanf () function succeeds is the number of variables that were successfully read, that is, you have a scanf () function with several variables, and if the scanf () function reads all the time, 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 scanf ()-function is a universal terminal format input function that reads input information from a standard input device (keyboard). You can read any intrinsic type of data and automatically transform the values into the appropriate in-machine format.
SSCANF ()-Reads data in a string that matches the specified format.
Function Prototypes:
Int sscanf (String str, String fmt, mixed var1, mixed var2 ...);
int scanf (const char *format [, argument] ...);
SSCANF is similar to scanf, which is used for input, except that the latter takes a screen (stdin) as the input source, the former with a fixed string as the input source.
Where format can be one or more {%[*] [width] [{h | l | I64 | L}]type | ' ' | '/T ' | '/n ' | Non-% symbol}
such as: sscanf ("123456", "%s", buf);
Puts (BUF); The result is: 123456
The following is mainly about the use of scanf ():
General form of the scanf function
SCANF (format control, Address table column)
int scanf (char *format[,argument,...]);
The meaning of "format control" is the same as the printf function; "Address table column" is a table column consisting of several addresses, which can be the address of a variable or the first address of a string.
The scanf () function returns the number of data items that were successfully assigned, and EOF is returned when an error occurs.
Note: whitespace characters (including/n,space) in scanf () cause the scanf () function to omit 0 or more whitespace characters from the input in the read operation, and the whitespace can be space,tab, newline, and so on, until the first non-whitespace character appears. The next format character is also the same as%c. For example, scanf ("%d%c", &i,&ch); Input: One A enter, i=11,ch=a. Here ch is not a space.
A non-whitespace character causes the scanf () function to reject characters that are the same as this non-whitespace character when read.
such as: scanf ("%c", &ch); Input: After a number of carriage returns, enter a, ch=a.
scanf ("5729%s", str);  Input: 5729okok Str=okok. However, please note: When the first few inputs are not 5729 (even if you start with a space!), an error will occur, and the STR value is unchanged.
Description of format characters in scanf ()
%p read in a pointer
%[] Scan Character Set
%n the equivalent number of characters that have been read into the value
%s reads a string, ending with a space, tab, or line break.
%c%d%i%o%x%x%c
%f enter real numbers, which can be entered in decimal or exponential form.
%F%e%e%g%g
%u read in an unsigned decimal integer
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
m specifies the width of the input data
* Asterisk empty read a data
The actual routines are described:
One: "%d%d%d"
is to enter three values in the decimal value format. When entering, the two data can be separated by one or more spaces, tab keys, and enter.
"%d,%d,%d"
The runtime enters three values as follows: 3,4,5↙ (input a,b,c value) or 3,-4,-5↙ (input a,b,c value) 3,---4,-5↙ (input a,b,c value)
................

is legal, but the input 3-,4--,5↙ error!!!!

Because the normal characters in the format string of scanf () are fully matched!
%c
When entered with "%c", both spaces and "escape characters" are valid characters.

Two: the scanf () function starts the input of a data with a non-whitespace character (including spaces, jumps, carriage returns) (of course, except for%c!), but note that gets () starts with any character!).
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).
① the space, "enter", "Jump" key.
② to the end of the width.
③ in the event of illegal input. It is important here that if there is an illegal input, the input of this data is ended, but the illegal data entered is still in the buffer, you can receive it with the corresponding data type! You can simply clear the buffer.
For example:
i=10;
scanf ("%s", str);
scanf ("%d", &i);
scanf ("%s", str2);
printf ("%s/n", str);p rintf ("%d/n", i);p rintf ("%s/n", str2);
Input: I love!
Output: I
10

love!

Because love is a start input for%d (scanf () starts with a non-whitespace), but because it is illegal,

So the beginning is the end, I value does not change!
Three. The scanf () function can correctly accept strings with spaces. such as: I love c!

In fact, it can!!!
Char str[80];
scanf ("%s", str);   Input I love c? Result: Output I
Analysis: scanf () The space after scanning to "I" is considered to be the end of the assignment to STR and ignores the following "Love c!". Here's the "Love c!" note. Also in the keyboard buffer
After debugging found that, in fact, the buffer string pointer is already equal, that is, the buffer is emptied, the scanf () function should just scan the stdin stream, the remaining information is in the stdin.

In fact, I have tried, with scanf ("%s", str) input 127 consecutive characters, the keyboard buffer will not fit, that is, the input does not do processing, continue to input, there is no response, only the input enter is valid.

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 (3); /* Wait here for 3 seconds to tell you where the program is running */
scanf ("%s", str1); /* These two sentences do not need to be entered again, is the keyboard disk buffer re-scan */
scanf ("%s", str2); /* These two sentences do not need to be entered again, is the keyboard disk buffer re-scan */
printf ("/n%s", str1);
printf ("/n%s", str2);
return 0;
}
Input: I love c!
Output:
I
Love
C!
So, how do you enter a string with a space?
With Get () of course, but we can also use scanf (), because, scanf () also has a we do not use the input format: "%[]"
Special:%*[width] [{h | l | I64 | L}]type indicates that the condition is filtered out and no value is written to the target parameter
Supports collection operations://similar to regular expressions.

%[a-z] means match any character in a to Z, greed (as many matches as possible)//or:%[a-z1-9] The end of a non-a~z,1~9.
%[ab ' matches a, B, ' a member, greed//to a non-B, ' The end of the character.
%[^a] matches any character of non-A, greedy scanf ("%[^a]", str);

Input: Ffddssaaff extracts the FFDDSS into the string str. That is, scan to a immediately as the end.
Therefore, we can use scanf ("%[^/n]", str); To enter a string with a space. Input: L love c! Enter, then STR is I love c!
So scanf ("%*[^/]/%[^@]", str);  The role of??? Enter a string to intercept/to the string between @ ...

Four: Solve the problem of the keyboard buffer pollution. That is, the residual information, this is very important.
For example:
scanf ("%c", &AMP;C1);
scanf ("%c", &AMP;C2);
When input: A returns to B returns the value of the output C1,C2: it is obvious that C2 is not B.
Reason: The c2 is represented by int, and see what the scanf () function assigns to C, and the result is c2=10.
What is the ASCII value of 10. Line break is/N.
Each of US hits the "Enter" key, sends a "carriage return" (/R) to the keyboard buffer, and a "newline" (/N).
Here/R is disposed of by the scanf () function (let's say ^_^), and/n is assigned to C by the scanf () function "wrong".
As if using Getch (), hit enter, receive a carriage return, and it does not pass from the keyboard buffer, that is, the keyboard buffer content is irrelevant!!!!!
I did a little experiment:
scanf ("%3s", str);
Puts (str);
C1=getch ();
printf ("C1%d/n", C1);
C2=getchar ();
printf ("C2%d/n", C2);
Input Aaabcdef output AAA input A output: 65,98 you see that!!!
%3s only receives AAA, then enters a, is received by Getch (), and after the output, GetChar () continues to remove B from the buffer, understood.
The best way to solve this type of problem is to add a fflush (stdin) after two scanf () functions. Function: Clear a stream usage: int fflush (FILE *stream);
In addition, Baidu Encyclopedia there is another way: with GetChar () and Getch () to receive. However, as we can see from the previous experiment, getch () does not handle the buffer and does not handle the residual information of scanf ().
You can try it:
scanf ("%c", C1);
Getch (); Suppose to be used to receive line breaks.
scanf ("%c", C2);
After entering a carriage return: The C1 value is 65,C2 13, which is a newline.

In fact, Getch () will wait for an input.
After the Getch () is changed to GetChar (), enter: A enter B Enter, output a B

Five: The following procedure to enter two number, the program will not end, rather than the expected one, why?

#include <stdio.h>
  int main ()
  {   
  int A;
  printf ("InP UT the data/n ");
  scanf ("%d/n", &a);      //Here is a carriage return/n, if used scanf ("%d ", &a);     printf ("%d", a);              ///The same problem will occur.
  return 0;
 }
  //input: 11 Return to the car  , no output, and then enter a space, return, TAB, any number of, no output, when entering non-whitespace characters such as input ABC return, only output, output is 11.
 //analysis of its cause (not necessarily accurate, it should be possible to explain it):
     scanf () is a terminal format input function, that is, by matching the variable to assign value!!  
      rules  :  For example, "%d/n":

The first space can match any number of whitespace characters in the input buffer (including spaces, carriage returns, Tab), and when the first non-whitespace character is met, the match is ended, and%d is processed.
%d can be matched with a continuous number symbol, and when the first non-numeric symbol is encountered, the match is ended, and if it matches a number of 0, the value of%d corresponding variable is unchanged.//Note that%d starts a match with any non-int character, even if '. ' Is no exception, such as entering 12.30.30 is not read, but is left in the buffer.
Similarly,/n also matches one or more enter,tab,space until the first non-whitespace character is encountered.
Also for "%d": matches the first non-whitespace character in the buffer.
However, "%c" is an exception, it matches the first character in the buffer, regardless of whether it is blank or not, so when processing the input character +enter, be sure to take note of the Enter.
So for the above example, the input is: 11a, the carriage return can output 11, but do not forget that the buffer also has a and/n!!!

VI: About STDIN, in fact, it is a standard input file, which is of type *.

Therefore, scanf ("%s", str); Also equivalent to fscanf (stdin, "%s", str);

   but scanf () can only be used to enter 127 characters or less, that is, the buffer can only be loaded with 127 characters + '/', then why Stdin->bsize is 512?  //under TC.

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.