1: scanf functions, carriage return, space, and returned values

Source: Internet
Author: User

Relationship between scanf and carriage return:

Let's first look at a frequently used code:

  char c;  scanf("%c", &c);

Among the various formats of scanf, % d, % C, and % s are the most commonly used. Generally, return keys are used as the end of an input. Due to different Character Parsing methods and character characteristics (for example, special characters such as space and carriage return are not displayed in numbers), The % d format generally does not encounter problems during continuous input. However, % s and % C may encounter various problems, such as carriage return and space.

We are used to the above Code. Let's look at the following code.Continuous input:

  int i;  char c;  scanf("%d", &i);  scanf("%c", &c);

If we assign a value of 3 to I and end the assignment to I by pressing the carriage return. When you assign values to C in the conventional way, you will find that C is not assigned a value for C, and C is automatically assigned a value of 10 in decimal format, that is, the Return key.Why ???

To answer this question, first readFunctions and working principles of scanf Functions:

 Scanf function is used to obtain the input value from the standard input device and store it To the memory unit pointed to by the pointer in the parameter list. If the read is successful, the function returns the number of data records that have been successfully read. The scanf function usually ends with three types of data. The common ending method is space, carriage return, or tab; you can also control the end based on the specified format controller, such as the format of the % 5d class. If an illegal input is encountered, the end is automatically ended.

For common three formats, the ending symbols are as follows:

% D format input, The default Delimiter is all white-spaces (spaces, carriage return, tabulation );

% C format input, Which is based on ASCII characters and has no delimiters. It may be affected by the previous input. If necessary, use fflush (stdin) to clear the buffer;

% S is a stringThe default Delimiter is all white-spaces. The ending character "\ 0" is automatically added after the input ".

Continuing with the problems caused by continuous input above, the buffer zone is involved.The scanf function reads data from the buffer zone in the form of deletion (the buffer zone stores data from standard input ).If the buffer zone is empty, block it and wait for input from the keyboard. scanf can also ignore leading blank characters such as \ n \ t and spaces for number input. (Note, for character input, the pilot character is not ignored. This is also a natural principle, because \ n \ t and space are both valid characters ).

  Scanf's buffer mechanism and Character Processing Method cause various exceptions when scanf reads characters % C and strings % S.For example, in the above example, analyze the Code:

Enter the value of I to 3 and press Enter. The data in the current buffer is "3 \ n". As a result, scanf reads a data controlled by % d from the buffer, that is, 3. "\ n" is left in the buffer. The format control for the next scanf function is % C. In this case, the leading blank character \ n is not ignored, instead, it is directly assigned to the character C. To view the buffer content, stdin [S1]. If you want to view the content in the current stdin, the general method is inverse, you can try to use the file operation freopen to redirect data in stdin to another file. This is another article.

  How can we solve this buffer zone and Character Parsing problem? Since there is something we don't need in the buffer zone, clear the buffer zone.. In Microsoft system, the fflush (stdin) function can clear the buffer, while in some compilation systems, the fflush operation on stdin is not defined, and the data in stdin is read out:

1) AvailableFgets () functionThis function has no compiler restrictions;

2) or give the excess in the buffer to other functions, suchGetchar (), The specific code is while (C = getchar ())! = '/N' & C! = EOF );

3) the above method is based on the principle, but it is a little troublesome, especially when the character % C and string % s are used to process the carriage return. C also providesGets () functionThis problem is solved. The gets () function is read in regardless of any character in the middle until a carriage return occurs;

4) In C ++, you can also operate stdin pointers. stdin is a file * type data structure that enables stdin-> _ io_read_ptr = stdin-> _ io_read_end ;. But not in C.

 

Scanf and Space key

As mentioned above, the scanf function processes white space characters in different formats.In % d format, it is not sensitive to white space characters and usually serves as the Terminator. For % C, it is sensitive to carriage return characters. spaces are processed as common characters; for % s, carriage return and space are both the ending characters of the current function. Due to the stdin mechanism of the buffer zone, special attention should be paid to the influence of space and carriage return on % S.

  % S default Delimiter is all white-spaces. After the input, the Terminator "\ 0" is automatically added to make it a string (the reason why \ 0 is added, it is related to the ending character of the character array char []. C does not have the string type, and uses the char [] structure to implement the string ). It is worth noting that, even if the length of the input character is sufficient, % s would rather discard the input character and add/0 as the end of the string.In addition, scanf ignores spaces at the beginning of the buffer. It knows that a non-space character is encountered before it starts to read data from the memory.

For example, if we want to input "the C programming language. \ n", how can we deal with the space in the middle?

  One solution is to use the gets function.This function uses a carriage return as the marker for the end of the input;Another solution is scanf ("% [^ \ n]", c):

  char c[15];  scanf("%[^\n]", c[s2] );

Only scanf ("% [^ \ n]", C); and gets do not ignore all spaces, including spaces starting with the buffer; this is different from scanf ("% s", c);. % s is used to ignore spaces at the beginning of the buffer.

 

In addition, the return value of scanf

The value returned by the scanf () function is: Enter the number of variables correctly in the specified format, that is, the number of variables that can correctly receive the value. When a type match error occurs, exit abnormally. You can use the return value of the scanf function to determine whether the input is correct and control the process:

     int i = 0;     char c1[15];     while((scanf("%c", &c1[i])!=EOF) && i<14)     {              i++;     }

 

 [S1]Stdin is a standard input, generally for the keyboard, and is a file * type data.

 [S2]Pay attention to whether to use C or & C:

C is an array. An array represents the first address of the array. Therefore, you can use C;

& C indicates the address of array C, that is, the first address. But C is generally more logical. This can be explained when reading data of the % S type:

Scanf ("% s", c );

 

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.