In layman's scanf, Getcha, gets, cin functions

Source: Internet
Author: User

Goto: Problem Description One: (Parse scanf () and GetChar () read characters)


scanf (), GetChar () and so on are standard input functions, and the average person will find these functions very simple, nothing special. But sometimes it is because the use of these functions, but the problem, but can not find out why. Let's look at a very simple program:
Program 1:
#include <stdio.h>
int main ()
{
Char Ch1, CH2;
scanf ("%c", &ch1);
scanf ("%c", &AMP;CH2);
printf ("%d%d\n", CH1, CH2);
return 0;
}
 or is:
#include <stdio.h>
int main ()
{
Char Ch1, CH2;
CH1 = GetChar ();
CH2 = GetChar ();
printf ("%d%d\n", CH1, CH2);
return 0;
}
The program is simply meant to read two characters from the keyboard and then print out the ASCII values of the two characters. But after the execution of the program will find that except the problem: When you enter a character from the keyboard, print out the results, there is no input of the second word Fu Chengxu will end. For example, the user enters the character ' a ', the print result is 97, 10. What is this for?
"Analysis":
First of all, let's take a look at the principle of input operation, the input of the program has a buffer, that is, the input buffer. The first input process is this, when the input data is stored in the input buffer at the end of the keyboard input, and the CIN function takes the data directly from the input buffer. Because the CIN function takes data directly from the buffer, sometimes when there is residual data in the buffer, the CIN function directly obtains the residual data without requesting the keyboard input, which is why the input statement fails in the example!
    in fact, the 10 here happens to be a carriage return! This is because the scanf () and GetChar () functions read values from the input stream buffers, not from the keyboard (that is, the terminal) buffer. While reading the end of a carriage return (\ n), this will read into the input stream buffer together, so the first time to accept input when the character will leave the character \ n, so that the second read into the function directly from the buffer to take away, obviously read successfully, so no longer read from the terminal! This is why this program only performs one input operation at the end of the reason!

----------------------------------------------------
| Problem Description Two: (Parse scanf () and gets () read string) |
----------------------------------------------------
First, let's take a look at the problem with scanf () reading the string:
Program 2:
#include <stdio.h>
int main ()
{
Char str1[20], str2[20];
scanf ("%s", str1);
printf ("%s\n", str1);
scanf ("%s", str2);
printf ("%s\n", str2);
return 0;
}
The function of the program is to read into a string output and read in a string output. We may find that there are no spaces in the input string, for example:
Test one input:
Hello world!
Output:
Hello
world!
"Analysis" until this program executes, the second read operation is not performed! The cause of this problem is similar to the problem, after the first input of Hello world!, the string Hello world! will be read into the input buffer, and the scanf () function takes the data is encountered carriage return, space, Tab will stop, that is, the first scanf () will take out "Hello ", and" world! " is still in the buffer so that the second scanf will take the data out directly without waiting for input from the terminal.

Test Two:
Hello[enter]
hello[Output]
World[enter]
world[Output]
The analysis program executes two reads from the keyboard, stating that the carriage return at the end of the first input is discarded! That is: scanf () reads the string and discards the last carriage return!


Let's see what gets () reads the string:
When using scanf to read a string, the string is not allowed to appear in the space, once a space appears, the subsequent data will discard the remaining in the buffer. In fact, there is another function can accept the space, that is get (), the following we look at the application of this function, we change the program 2:
Program 3:
#include <stdio.h>
int main ()
{
Char str1[20], str2[20];
Gets (STR1);
printf ("%s\n", str1);
Gets (STR2);
printf ("%s\n", str2);
return 0;
}
Test:
Hello world! Input
Hello world! Output
12345 [input]
12345 [Output]
"Analysis" is obviously different from the execution of the previous program, this time the program performed two reads from the keyboard, and the first string took the Hello world! Accepts a space character without dividing it into two strings like the last program! So if you want to read a string with a space character due to the use of get (), rather than using scanf ()!


--------------------------------------------------------
| Problem description Three: (GetChar () pause the program to see the results of the program execution) |
--------------------------------------------------------
Do not know if you have encountered such a problem, some compiler program after execution of the result interface will not stop but a flash of the lost, so that the results can not be seen. So many people at the end of the program with the GetChar () statement, the purpose is to let the program to stop after execution, waiting to receive a character from the terminal and then end the program. But found that sometimes such a useless, the program still jumped out. What is this for?
The reason for "analysis" is the same as in the above example, because there is data in the input buffer, so GetChar () will read the data, so it jumps out!

------------------
| "Summary" |
------------------
First: pay attention to whether the different functions accept whitespace, whether to discard the last carriage return problem!
When reading characters:
scanf () ends the input with space, enter, tab, and does not discard the last carriage return (that is, the carriage return remains in the buffer);
GetChar () ends the input with enter and does not discard the last carriage return;
When reading a string:
scanf () end one input with space, enter, tab
Gets () ends the input with enter (the space does not end), accepts the space, discards the last carriage return!

Second: in order to avoid this problem, you must clear the buffer residual data, can be resolved by the following methods:
The 1:c method provides a function to empty the buffer in the language, so long as the buffer is emptied before reading the data, no problem!
This function is Fflush (stdin).
Method 2: Remove the residual data from the buffer itself.
(To tell the truth this statement I did not read, hehe!) Why is the format control like this! I hope the expert pointed out! )
scanf ("%[^\n]", string);

2-cin-In-depth analysis (on)-CIN input Operation processing

Cin<<, Cin.get,cin.getline and other functions in-depth analysis

Many beginners think that the CIN function is a very simple function, not really! The CIN function has a lot of knowledge to understand (for example, what the return value of CIN is, what member functions CIN provides and what the roles are, such as cin.clear (), Cin.ignore (), Cin.fail (), Cin.good (), and so on), If not well mastered, in the use of the time is likely to be a problem but do not know why! And a lot of people are actually experiencing a lot of problems, here are a few simple examples:

Program 1:

#include <iostream>

using namespace Std;

int main ()

{

int m, n;

cin>>m;

cin>>n;

return 0;

}

Test situation:

If the user enters two legal number each time, the program does not have the problem!

However, if the user gives an illegal input for the first time, such as entering a character ' a ', you will find that the program does not

The second input statement is executed again. It seems a little strange!!

Program 2:

#include <iostream>

using namespace Std;

int main ()

{

Char Str[8];

Cin.getline (str, 5);

cout<<str<<endl;

Cin.getline (str, 5);

cout<<str<<endl;

return 0;

}

The function of the program is simple, just enter a string and then output again, enter a string output again. Implementation of the program:

Test One:

ABCD (carriage return)

ABCD (output)

EFGH (carriage return)

EFGH (Output)

When the number of characters entered by the user for the first time is less than 4 o'clock, the program executes normally!

Test Two:

ABCDEFGH (carriage return)

ABCD (output)

(Output-line wrapping)

When the user first enters a number of characters that are greater than 4 o'clock, the first string accepts the first four characters of the input, and the second input operation is not executed, and the second string output is empty. It seems strange too!!!

In fact, in many cases will encounter such problems, if not familiar with the principle of program input and CIN and other functions of the principle of not know how to solve! I am here to do a simple introduction, perhaps the introduction is not very accurate and comprehensive, or there are some misunderstandings, please forgive us!

How the input operation works

As with the scanf function mentioned in the previous section, the input of the program is built into a buffer, which is the input buffer. The first input process is this, when the input data is stored in the input buffer at the end of the keyboard input, and the CIN function takes the data directly from the input buffer. Because the CIN function takes data directly from the buffer, sometimes when there is residual data in the buffer, the CIN function directly obtains the residual data without requesting the keyboard input, which is why the input statement fails in the example!

Cin some of the input functions and operators

CIN is a extern istream object. Provides a number of available member functions and overloaded operators, such as: Cin<<, Cin.get (), Cin.getline (), and so on. Let's take a look at some of these functions:

I. cin<<

The operator reads the data according to the type of the subsequent variable.

Enter end condition: Encounter Enter, Space, TAB key. (This is important!) )

Handling of Terminator: Discard Terminator (Enter, Space, TAB) in the buffer that makes the input end

The case of reading characters:

Program 3:

#include <iostream>

using namespace Std;

int main ()

{

Char C1, C2;

cin>>c1;

cin>>c2;

cout<<c1<< "" <<c2<<endl;

return 0;

}

Test one input:

A[enter]

B[enter]

Output:

A b

Test two inputs:

A b[enter]

Output:

A b

The case of reading a string:

Program 4:

#include <iostream>

using namespace Std;

int main ()

{

Char str1[10], str2[10];

cin>>str1;

cin>>str2;

cout<<str1<<endl;

cout<<str2<<endl;

return 0;

}

Test one input:

Abcd[enter]

Efgh[enter]

Output:

Abcd

Efgh

The "parse" input encounters a carriage return end, which is normal.

Test two inputs:

ABCD EFGH

Output:

Abcd

Efgh

Parsing reads a string the first time it encounters a space, it stops, it reads ABCD into STR1, and discards the space, giving the next string a second string. This proves that CIN reads the data to the end of the space, and discards the whitespace, the buffer has a residual data room, and the read-in operation takes the data directly from the buffer.

Two Cin.get ()

The function has three formats: no parameter, one parameter, two parameters

i.e. Cin.get (), Cin.get (char ch), Cin.get (Array_Name, Arsize)

To read a character:

Enter end condition: Enter key

Processing for Terminator: Do not discard the enter in the buffer

Cin.get () and Cin.get (char ch) are used to read characters, their use is similar,

That is, Ch=cin.get () is equivalent to Cin.get (CH).

Program 5:

#include <iostream>

using namespace Std;

int main ()

{

Char C1, C2;

Cin.get (C1);

Cin.get (C2);

cout<<c1<< "" <<c2<<endl; Print two characters

cout<< (int) c1<< "" << (int) c2<<endl; Print the ASCII value of these two characters

return 0;

}

Test one input:

A[enter]

Output:

A

97 10

Analysis will find that only one time from the keyboard input, obviously the first character variable takes the ' a ', the second variable takes the ENTER (ASCII value is 10), because the function does not discard the last input at the end of the Enter character, So at the end of the first input, the buffer remains the enter character at the end of the last input!

Test two inputs:

A b[enter]

Output:

A

97 32

"Analysis" Obviously the first character variable takes the ' a ', the second variable takes space (ASCII value is 32). For the same reason, the space character is not discarded.

To read a string:

Cin.get (Array_Name, arsize) is used to read a string, can accept a space character, encounters a enter end input, reads a character by length (arsize), and discards the last enter character.

Program 6:

#include <iostream>

using namespace Std;

int main ()

{

Char a[20];

Cin.get (A, 10);

cout<<a<<endl;

return 0;

}

Test one input:

ABC Def[enter]

Output:

ABC def

Analysis indicates that the function can accept spaces when it enters a string.

Test two inputs:

1234567890[enter]

Output:

123456789

The analysis input is long, and the data is taken at the desired length.

Program 7:

#include <iostream>

using namespace Std;

int main ()

{

Char ch, a[20];

Cin.get (A, 5);

cin>>ch;

cout<<a<<endl;

cout<< (int) ch<<endl;

return 0;

}

Test one input:

12345[enter]

Output:

1234

53

"Analysis" The first time the input is very long, the string by the length of "1234", and ' 5 ' is still left in the buffer, so the second input character is not read from the keyboard, but directly take the ' 5 ', so the printed ASCII value is 53 (' 5 ' ASCII value).

Test two inputs:

1234[enter]

A[enter]

Output:

1234

97

"Analysis" The second input is valid, indicating that the function of the first input after the Enter discarded!

Three Cin.getline ()

Cin.getline () and Cin.get (Array_Name, arsize) read the same way, ending with enter, you can accept the space character. Reading a character by length (arsize) discards the last enter character.

But there are differences between the two functions:

Cin.get (Array_Name, arsize) when the input string is very long, it does not cause an error in the CIN function, and subsequent CIN operations continue, just fetching data directly from the buffer. However, cin.getline () will cause an error in the CIN function when the input is very long, and the subsequent CIN operation will no longer execute. (Specific reasons are described in detail in the next section, "Error handling in CIN")

Program 8:

#include <iostream>

using namespace Std;

int main ()

{

Char ch, a[20];

Cin.getline (A, 5);

cin>>ch;

cout<<a<<endl;

cout<< (int) ch<<endl;

return 0;

}

Test input:

12345[enter]

Output:

1234

-52

"Analysis" and Cin.get (Array_Name, arsize) of the routine comparison will find that the CH is not read in the buffer 5, but return 52, here in fact the CIN>>CH statement is not executed, because CIN error!

In layman's scanf, Getcha, gets, cin functions

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.