Problems with the gets function for a character array consecutively (buffer content supplement)

Source: Internet
Author: User
Tags function prototype

Yesterday the debugger (see code below) encountered the following problem:

#include <stdio.h>int main () {int i = 1;while (i) {char str[100];p rintf ("Please input a str:\n"), gets (str);        Puts (str);p rintf ("continue:1,break:0\n"); scanf ("%d", &i);} return 0;}


Hey!!! I have not entered the string from the keyboard, how did he do the next step???????

To debug your code:



Memory at this time:



Then click Next:


Hey?????? "----->> 0 <<-----" in the array where did you get it??? The solution is not to be thought of!

Consult a large amount of data originally related to buffer, first understand the following buffer:

Understanding of buffer in C + + programming

What is a buffer
A buffer is also known as a cache, which is part of the memory space. In other words, a certain amount of storage space is reserved in the memory space, which is used to buffer the input or output data, which is called the buffer space.
The buffer is divided into input buffers and output buffers depending on whether it corresponds to an input device or an output device.

Why to introduce buffers
Why do we have to introduce buffers?
For example, we take the information from the disk, we first put the read data in the buffer, the computer then take the data directly from the buffer, and so on after the buffer data is fetched to the disk to read, so that can reduce the number of disk read and write, plus the computer to the buffer operation is much faster than the operation of the disk, Therefore, the application of buffer can greatly improve the speed of computer operation.
For example, we use the printer to print the document, because the printer printing speed is relatively slow, we first output the document to the corresponding buffer of the printer, the printer and then gradually print themselves, then our CPU can handle other things.
Now you basically understand that the buffer is a block of memory that is used between the input and the CPU to cache the data. It enables low-speed input and high-speed CPUs to work in a coordinated manner, avoiding low-speed input consuming the CPU and freeing the CPU to work efficiently.

Type of buffer
There are three types of buffers: full-buffered, row-buffered, and unbuffered.
1. Full buffer
In this case, the actual I/O operation is not performed until the standard I/O cache is filled. A typical representation of a full buffer is the read and write of a disk file.
2, Row buffer
In this case, the real I/O operation is performed when a newline character is encountered in the input and output. At this point, we enter the word Mr. Foo stored in the buffer, and so on when the return hit enter the actual I/O operation. The typical representation is keyboard input data.
3, without buffering
That is, no buffering, standard error stderr is a typical representative, which makes the error message can be displayed directly as soon as possible.
Refresh of Buffers
The following conditions cause a buffer refresh:
1, when the buffer is full;
2, execute FLUSH statement;
3, execute ENDL statement;
4, close the file.
It is visible that buffers are flushed when the buffer is full or closed, for true I/O operations. In addition, in C + +, we can use the flush function to flush buffers (performing I/O operations and emptying buffers), such as:
cout<<flush; Instantly output the contents of the video memory to the monitor for display

The effect of the Endl control is to move the cursor to the beginning of the next line in the output device and empty the buffer.
cout<<endl;
Equivalent
cout<< "\ n" <<flush;

Illustrate by example

1. File Operation Demo Full buffer
To create a console project, enter the following code:

#include <fstream>using namespace Std;int main () {    //create file Test.txt and open ofstream outfile ("test.txt");    Writes a 4,096 character ' a ' for (int n=0;n<4096;n++) {outfile<< ' A ' to the Test.txt file;}    Pause, press any key to continue system ("pause");        Continue to write the character ' B ' to the Test.txt file, meaning that the No. 4097 character is ' B ' outfile<< ' B ';    Pause, press any key to continue system ("pause"); return 0;}

The above code is easy to understand and has been commented inside the code.
The purpose of writing this small code is to verify that the full-buffered size of the windowsxp is 4,096 bytes, and that the buffer is flushed when the buffers are full, performing real I/O operations.

Compile and execute and run the following results:

When you open the Test.txt file in the folder where the project is located, you will find that the file is empty, which means that the 4,096 character "A" is still in the buffer and does not actually perform I/O operations. Hit the Enter key and the window changes to the following:

When you open the Test.txt file again, you will be sent a 4,096 character "a" in the file. This means that the full buffer size is 4K (4096), the buffer is full and I/O operations are performed, and the character "B" is still in the buffer.
Hit the enter key again and the window changes to the following:

When you open the Test.txt file again, you will notice that the character "B" is in it. This step verifies that the buffer was refreshed when the file was closed.

2, keyboard operation demo Line buffer
The GetChar () function is introduced first.
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 character entered by the user is stored in the keyboard buffer until the user presses ENTER (the carriage return character is also placed in the buffer). The GetChar () function starts to read one character at a time from the keyboard buffer when the user enters enter. That is, subsequent getchar () function calls do 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. No, in a more popular sense, when the program calls the GetChar () function, the program waits for the user to press the key, and so the user presses the Enter return. The characters that are pressed during the period are stored in the buffer, and the first character returns a value as a function. Continue calling the GetChar () function, instead of waiting for the user to press the key, return the 2nd character you just entered, continue the call, return the 3rd character, and wait for the user to press the key until the character in the buffer has been read.
If you do not understand, can only blame my limited ability to express, you can combine the following examples of experience.

To create a console project, enter the following code:

#include <iostream>using namespace Std;int main () {char c;//calls the GetChar () function for the first time//program execution, you can enter a string of characters and press ENTER, The function returns C=getchar () after pressing ENTER.    Displays the return value of the GetChar () function cout<<c<<endl;    Pause System ("pause"); The loop calls the GetChar () function multiple times//The return value of each call to the GetChar () function is displayed//until the carriage return is met ((C=getchar ()) = ' \ n ') {printf ("%c", c);}    Pause System ("pause"); return 0;}

This small code is also very simple, there are comments inside the code.
The execution of the GetChar () function is the use of a row buffer. The first call to the GetChar () function causes the program consumer (user) to enter a line of characters and return until the ENTER function is pressed. The character and carriage return entered by the user at this time are stored in the row buffer.
Calling the GetChar () function again will progressively output the contents of the row buffer.
Well, I have limited ability to express, or compile and run the program, through the results of their own understanding it.

Compile and run the program, you will be prompted to enter characters, you can alternately press some characters, as follows:

You keep pressing down and you'll notice that when you press the No. 4094 character, you're not allowed to continue entering characters. This indicates that the size of the row buffer is also 4 K.
At this point you press ENTER to return the first character ' a ', such as:

Continue tapping the ENTER key to output all other characters of the buffer, such as:

3, standard error output without buffering
If the error output is used:

cerr<< "error, please check the input parameters!";

This statement is equivalent to:
fprintf (stderr, "error, please check the input parameters!");

OK, let's talk about it, good luck and hope to help you.

The above content is connected from: http://www.cnblogs.com/charm/archive/2010/08/17/1801419.html

Although some pictures can not be seen, but the blogger's description makes me benefit!!!

See here our first problem is solved:

scanf ("%d", &i);
After executing the code, 1 is assigned to I-------->>>>> but newline character enter is left in the buffer, the next time the Get function, because the contents of the buffer, the GET function is no longer waiting for user input, but directly from the buffer read content.

Because the gets function is as follows:



' ====0 ' (value equal---->>>>ASCII 0 is null), which is the reason to start looking at memory, ASCII0 exists!!!



Problems with the gets function for a character array consecutively (buffer content supplement)

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.