Problems with the continuous use of the gets function for a character array (buffer content supplement)

Source: Internet
Author: User

Problems with the continuous use of the gets function for a character array (buffer content supplement)

Yesterday, the program debugging (see the following code) encountered the following problem:

 

#include
 
  int main(){int i = 1;while(i){char str[100];printf(please input a str:);gets(str);        puts(str);printf(continue:1,break:0);scanf(%d,&i);}return 0;}
 


 

Success !!! I have not input a string from the keyboard. How can I perform the next step ???????

Debug the Code:

 

Memory:

 

Click next:

Why ?????? Where does "-----> 0 <-----" in the array come from ??? Think twice!

Reading a large amount of data is originally related to the buffer zone. First, let's take a look at the buffer zone:

 

C ++ programming's understanding of the buffer zone

What is a buffer?
A buffer is also called a cache, which is a part of the memory space. That is to say, a certain amount of storage space is reserved in the memory space, which is used to buffer input or output data. This reserved space is called a buffer zone.
The buffer zone is divided into the input buffer zone and the output buffer zone based on whether it is an input device or an output device.

Why introduce a buffer?
Why should we introduce the buffer?
For example, if we retrieve information from a disk, we first put the read data in the buffer zone, and then the computer directly retrieves data from the buffer zone, and then reads the data from the disk after the buffer zone is obtained, in this way, the number of reads and writes to the disk can be reduced. In addition, the computer's operations on the buffer zone are much faster than those on the disk. Therefore, the application buffer can greatly improve the computer's operation speed.
For another example, we use a printer to print documents. Because the printer printing speed is relatively slow, we first output the documents to the corresponding buffer zone of the printer, and then print them gradually, at this time, our CPU can handle other things.
Now, you basically understand that the buffer zone is a memory zone, which is used to cache data between the input and output devices and the CPU. It allows low-speed input/output devices and high-speed CPUs to coordinate work, avoiding low-speed input/output devices occupying CPU, freeing them from CPU, and enabling them to work efficiently.

Buffer type
There are three buffer types: Full buffer, row buffer, and no buffer.
1. Full Buffer
In this case, the actual I/O operation is performed only after the standard I/O cache is filled. A typical example of full buffer is read/write of disk files.
2. Row Buffering
In this case, when a line break is encountered in the input and output, the real I/O operation is executed. At this time, the entered characters are first stored in the buffer, and the actual I/O operation is performed only when the Enter key is changed. A typical example is keyboard input data.
3. No Buffer
That is, stderr is a typical example of standard errors, which allows error information to be displayed as soon as possible.
Refresh the buffer
In the following cases, the buffer is refreshed:
1. When the buffer is full;
2. Execute the flush statement;
3. Execute the endl statement;
4. close the file.
It can be seen that when the buffer is full or the file is closed, the buffer is refreshed for real I/O operations. In addition, in C ++, we can use the flush function to refresh the buffer (execute the I/O operation and clear the buffer), for example:
Cout <

The endl controller moves the cursor to the beginning of the next line of the output device and clears the buffer zone.
Cout < Equivalent
Cout <"<

Demo by instance

1. File Operation demonstration full Buffer
Create a console project and enter the following code:

# Include
         
          
Using namespace std; int main () {// create the file test.txt and open ofstream outfile(test.txt); // write the 4096 character 'a' for (int n = 0; n <4096; n ++) {outfile <'a';} // PAUSE, press any key to continue system (PAUSE); // write the character 'B' to the test.txt file in succession ', that is to say, the 4,097th characters are 'B' outfile <'B'; // paused. Press any key to continue system (PAUSE); return 0 ;}
         

The above code is easy to understand and has been commented out in the Code.
The purpose of writing this small code is to verify that the buffer size in Windows XP is 4096 bytes. After the buffer is full, the buffer is refreshed and the real I/O operation is performed.

Compile and execute the command. The running result is as follows:

When you open the test.txt file under the project folder, you will find that the file is empty. This indicates that the 4096 character "a" is still in the buffer zone and the I/O operation is not actually performed. Press enter. The window is changed to the following:

Then open the test.txt file, and you will see that the file already contains 4096 characters "". This indicates that the size of the full buffer zone is 4 K (4096). When the buffer zone is full, I/O operations are performed, and the character "B" is still in the buffer zone.
Press enter again and the window is changed to the following:

Then open the test.txt file, and you will find the character "B" in it. This step verifies that the buffer is refreshed when the file is closed.

2. keyboard operation demonstration row Buffering
First, we will introduce the getchar () function.
Function prototype: int getchar (void );
Note: When the program calls the getchar () function, the program waits for the user to press the key and the characters entered by the user are stored in the keyboard buffer, until you press enter (the carriage return character is also placed in the buffer ). After you press enter, the getchar () function starts to read one character each time from the keyboard buffer. That is to say, subsequent getchar () function calls will not wait for the user to press the key, but directly read the characters in the buffer until the characters in the buffer are read, and then wait for the user to press the key again.
I don't know if you understand it. In other words, when the program calls the getchar () function, the program waits for the user to press the key and waits for the user to press the return key. The characters pressed during this period are stored in the buffer zone. The first character is used as the return value of the function. To continue calling the getchar () function, you will not wait for the user to press the button, but will return the 2nd characters you just entered. To continue calling the function, 3rd characters will be returned until the characters in the buffer zone are read, wait for the user to press the button.
If you do not understand it yet, you can only complain that my expression capability is limited.

Create a console project and enter the following code:

# Include
         
          
Using namespace std; int main () {char c; // when you call the getchar () function for the first time, you can enter a string of characters and press the Enter key, after you press the Enter key, the function returns c = getchar (); // the return value of the getchar () function cout <
          

           

 

Compile and run the program, and you will be prompted to enter characters. you can press the following characters alternately: You keep pressing, you will find that when you press to 4,094th characters, you cannot enter more characters. This indicates that the row buffer size is also 4 K. Press the Enter key to return the first character 'a'. For example, press the Enter key to output all the other characters in the buffer zone, for example:

3. Standard Error output without bufferingIf error output is used:

Cerr <"error. Check the input parameters !";

This statement is equivalent to: fprintf (stderr, "error. Check the input parameter !");

Well, let's talk about it. Good luck and hope it will help you.

 

Although some images cannot be seen, I have benefited a lot from the description of this blogger !!!

We can see that the first problem was solved:

 

scanf(%d,&i);
After the code is executed, 1 is assigned to I -------- >>>>> but the linefeed enter is left in the buffer. The next time you run the gets function, the buffer contains content, therefore, the gets function does not wait for user input, but directly reads content from the buffer zone.

 

The gets function is as follows:

 

''= 0 (the value is equal ---- >>>> ASCII 0 is NULL). This is why ASCII0 exists at the beginning !!!

 

 

 

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.