Getchar, scanf, and buffer

Source: Internet
Author: User

1. getchar () is stdio. the library function in H reads a character from the stdin stream. That is to say, if stdin has data, it can be directly read without entering it.

Getch () and getche () are library functions in conio. H. They are used to receive characters from the keyboard, and getchar carries echo.

The difference between the two functions is that the getchar () function waits for the input to end until press enter (provided that there is no data in the buffer). All input characters before the carriage return are displayed on the screen one by one. But only the first character is used as the return value of the function.

# Include "stdio. H" # include "stdlib. H" int main (void) {char C; while (C = getchar ())! = '\ N') // each getchar () reads one character printf ("% C", c) in sequence; // outputs printf ("\ n") as is "); system ("pause"); Return 0 ;}

When running the program, stop and wait for you to input a string. After the input is complete, it outputs the entire string you entered. Then, you do not mean getchar () is the first character returned?

Because the input string does not take the first character, it will discard the remaining string, and it is still in our memory, after we put the water in the gate, we can open it once and then let it go a little. Once we open it, we can let it go a little until it is cleared. The opening action here is equivalent to calling getchar () once (). The same is true for the input string. First, the input string is placed in the memory buffer. We call getchar () to output the nearest character in the buffer, that is, the first character output. After the output, it is released, but there is a string behind it, therefore, we use loops to release the first character in the memory one by one until the loop condition is met and exits.

In the example, '\ n' in the loop condition is actually the carriage return after you input the string, so it means that the loop ends until a carriage return occurs, while getchar () the function is waiting for the input (or the data in the buffer) to end until press enter, so the output of the entire string is realized. Of course, we can also change the loop condition, such as while (C = getchar ())! = 'A, of course, if you enter "12345a213123", it will only output the character before a, and the result is 12345.

Note again: getchar () is used to read data from the "stream", so the first getchar () accept the first character (not limited to carriage return characters, as shown in the preceding example) in the interrupted stream queue. If the stream queue is not empty, run getchar () continue to put the water in place until the carriage return is empty. If it is empty, run getchar () to stop waiting for your input. We use getch () why is it always waiting for user input? Because getch () receives data from the keyboard and receives data instantly, it does not read data from the stdin stream.

The following is my discussion:

First come a piece of code:

#include "stdio.h"#include "stdlib.h"int main(void){char c;for(;(c=getchar())!='a';)printf("%c",c);getchar();c=getchar();printf("%c",c);system("pause");return 0;}

Enter: ssss press ENTER

Get: ssss

Cursor (waiting for input)

Note: Because the character A has not been input, the program is not completed at this time. After Entering the for loop, the program has not exited. After you press enter, run C = getchar () and extract (for loop) from the buffer in sequence:'s, including the line break of the carriage return, and print out all of them ..

If we enter: ssssa press ENTER

Get: ssss cursor (waiting for input)

Note: When the program reads the character a, it jumps out of the for loop, but because we use getchar (); The linefeed '\ n' is cleared, followed by the first sentence c = getchar (); you need to enter a character (because ssssa is not followed by a new character), so the program is still not completed. If we comment out the getchar (); sentence, then c = getchar (); this line of code can read the carriage return symbol after ssssa, you can get the output as follows:

Ssss

Cursor (program ended)

The linefeed '\ n' in the carriage return in the input ssssa is read and output by c = getchar.

Summary:

All the characters entered by the keyboard are stored in the buffer. Once you press enter, getchar enters the buffer to read the characters. Only the first character is returned at a time as the value of the getchar function, if there are loops or enough getchar statements, all the characters in the buffer are read in sequence until '\ n '. To understand this, the reason why you input a series of characters is read in sequence is that the function of loop allows the repeated use of getchar to read characters in the buffer, rather than getchar to read multiple characters, in fact, getchar can only read one character at a time. If you want to cancel the effect of '\ n', you can use getchar (); to clear it. Here, getchar (); only gets' \ n
'But it is not assigned to any character variable, so it will not be affected. It is equivalent to clearing this character, note that the echo you see in ssss on the keyboard is exactly the function of getchar. If you use getch, you will not be able to see what you entered.

2. scanf

Scanf is a strange library function and has some defects, so many people do not need it. here we will give a brief introduction.

The scanf input string, integer, real type, and other data judgment methods are the same. Press enter, space, and Tab keys are considered to be the end of a data, of course, a character is the end.Carriage Return, space, and so on all have corresponding ASCII codes. Therefore, when using scanf to input characters, be careful when these characters are input as characters, when data such as string, integer, and real type are input as separators, they are not input into character arrays or variables.Of course, if the input format is not "% S % s" but "% s, % s" is a comma.

Here are a few examples:

#include "stdio.h"int main(void){char n1[10];char n2[10];scanf("%s",n1);scanf("%s",n2);printf("n1=%s,n2=%s",n1,n2);return 0;}

Input:

Hello press ENTER

World Press ENTER

The output is as follows:

N1 = Hello, n2 = wolrd cursor (program ended)

Here, "hello" is followed by Multiple Input carriage returns and spaces, which will not be assigned to N2, because when using the scanf function to input strings, they are only used as separators. In addition, when N2 is input, the carriage return following N2 is also used as a separator. Therefore, during the output, the content of N1 and N2 is simply output, but the carriage return line break is not output.

If you enter:

Hello press ENTER

Cursor (waiting for input)

It indicates that the carriage return is recognized as a separator, so the program requires you to input a string to assign it to N2.

In fact, there is a '\ n' in the buffer, and the program is changed to this:

# Include "stdio. H "int main (void) {char N1 [10]; char N2 [10]; char N3, N4; scanf (" % s ", N1 ); scanf ("% s", N2); printf ("n1 = % s, n2 = % s", N1, N2); N3 = getchar (); // N3 reads the carriage return character after N2 and outputs printf ("% C", N3); // N4 = getchar (); // printf ("% C ", n4); return 0 ;}

Input:

Hello press ENTER

World Press ENTER

Get:

N1 = Hello, n2 = wolrd

Cursor (program ended)

If you cancel the comments of the last two rows, the same input will be:

N1 = Hello, n2 = wolrd

Cursor (waiting for input)

It indicates that there is only one '\ n' in the buffer, and the second getchar requires you to enter another character. There are no characters in the buffer.

Scanf does not assign carriage return and space to strings but will assign characters, just like getchar. In this case, the existence of '\ n' should be considered.

For example:

#include "stdio.h"int main(void) {char n1[10];char n2;scanf("%s",n1);scanf("%c",&n2);printf("n1=%s,n2=%d",n1,n2);return 0;}

Input:

Hello press ENTER

Get:

N1 = Hello, n2 = 10 cursor (program ended) // 10 is the ASCII code of '\ n.

If you enter:

Hello, press enter with a space (you must have a carriage return, because scanf also needs to wait for the carriage return, which is '\ n' to read the buffer .)

Get:

N1 = Hello, n2 = 32 the cursor (end of the Program) // 32 is the ASCII code of the space.

If the output of the last sentence is n2 = % d and changed to N2 = % C, enter:

Hello press ENTER

Get:

N1 = Hello, n2 =

Cursor (program ended)

Is it possible to read '\ n' like getchar.

Summary:

If scanf does not input a character, the separator is carriage return. When spaces and Tab keys are used, the delimiter between the two data is only used to distinguish the two data, assign values to the two separated data values to the defined variables or arrays respectively. The delimiter between the two data is read from the buffer but does not work, of course, the last '\ n' will be left in the buffer unless it is read by getchar (); or scanf ("% C", & C.

Carriage return is required, whether it is getchar or scanf, as long as the function enters data through the buffer zone, it is waiting for the Return key '\ n' to enter the buffer zone. Here is an example of mixing integer data, strings, and characters:

#include "stdio.h"int main(void) {int a,b,c;char n1[10];char n2,n3;scanf("%d%d",&a,&b);scanf("%c",&n2);scanf("%d",&c);scanf("%s",n1);scanf("%c",&n3);printf("a=%d,b=%d,n2=%c,c=%d,n1=%s,n3=%c",a,b,n2,c,n1,n3);return 0;}

Input:

12 (a number of spaces or carriage return will not affect the result. Press enter here)

34 (the input is also required here, because scanf only has an integer data and there is no integer data in the buffer zone. A carriage return or space indicates that the data is over. The left space or carriage return is accepted by % C. Here, a carriage return is used. You can try a space)

45 jfdkjfa (Press ENTER)

Get:

A = 12, B = 34, n2 =

, C = 45, n1 = jfdkjfa, N3 =

Cursor (program ended)

Here we will explain the process: when the first two integer data types are input, scanf serves as the separator for both the carriage return and several spaces. Well, when scanf reads the separator (carriage return or space, the first integer data is sent to variable A, and the delimiter and the following integer data are left in the buffer. At this time, scanf then reads the delimiter first, but the input is still integer data (% d ), therefore, the separator is ignored. If the character % C (not the string % s) is required, the separator will be sent to the character variable in the form of a byte, just like N2 here. Similarly, we can know the stored procedures of C and N1. The final N3 is the last carriage return when the input is received.

Well, if you understand it here, let's look at the last example:

#include "stdio.h"int main(void){int a;char ch;scanf("%d",&a);ch=getchar();printf("%d,%c",a,ch);return 0;}

Input:

95 press ENTER

Get:

95,

Cursor (program ended)

Obviously, this is because the separator (Press ENTER) is read and output by getchar. if you add the following sentence: getchar ();

#include "stdio.h"int main(void){int a;char ch;scanf("%d",&a);getchar();ch=getchar();printf("%d,%c",a,ch);return 0;}

Input:

95 press ENTER

C press ENTER

Get:

95, C cursor (program ended)

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.