C Language Getch (), Getche (), and GetChar ()

Source: Internet
Author: User

This article is for reprint article , document contributor Wdzhangxiang personal website: Www.baidu.com/p/wdzhangxiang

First of all, don't forget to usegetch ()header file must be introducedconio.h, previously learned C language, we always like to use at the end of the program to add it, use it to achieve the program run out of pause does not quit the effect . If you do not add this sentence,TC2.0environment in which we usectrl+f9after compiling and running, the program returns toTCenvironment, we have no time to see the results, when we want to see the results, we will pressAlt+f5Back toDOSIt's troublesome to look at the results in the environment. And if you add a line at the end of the programgetch ();statement, we can dispense with theDOSSee the result of this step, because the program runs out and does not exit, but at the end of the program to stop the screen, press any key to return toTCenvironment. Well, let's see.getch ()What role did it play,getch ()is actually an input command, just as we usedcin>>when the program will stop waiting for you to enter, andCinthe difference is thatgetch ()the role is to receive a character from the keyboard, and does not display this character, that is, you press a key after it does not display on the screen what you press, and continue to run the following code, so weC + +you can use it to implement the "press any key to continue" effect, which is encountered in the programgetch ();this line of statement, it will suspend the program, and so you press any key, it receives the character keys before continuing to execute the following code.

You might ask, why are we inC + +Is not added at the end of the programgetch (), the explanation is that the software is always constantly updated, the bad place of course to be corrected,getch ()added to the end of the program, it is not assigned to any variable, so it is completely garbage code in this place, regardless of the program. C + +take this into account, so that every time the program runs out and does not quit, it automatically stops the screen and displays "Press any key ..."Call you to press any key to exit, which is likeC + +run the program in its environment and automatically add a line at the end of the programgetch ();statement, and a line of output statements is added before this line statementcout<< "Press any key ...";to prompt you to end the program, press any key to continue. In fact, we compiled the program at the end of the program itself will not stop, we can compile the generatedDebugdirectory to find this compiled application (extensionEXE), double-click in the folder to run it, and you'll notice the screen flashes a bitMS-DOSThe window is closed because the program automatically exits when it is finished and returns to theWindowsenvironment, of course, if we were inDOSEnvironment to run this program, we can directly seeDOSyou see the program running results on the screen because the program does not clear the screen after it finishes running.

There is also a statement, similar to getch () ,Getche (), which also needs to introduce the header file conio.h, then where is the difference between them? The difference is that getch () has no return display, andGetche () has a return display. What do you say? I'll give you an example and you'll see.

--------------------------------------

#include <stdio.h>

#include <conio.h>

void Main ()

{

Char ch;

for (int i=0;i<5;i++)

{

Ch=getch ();

printf ("%c", ch);

}

}

--------------------------------------

I'm using the input output here.CLibrary of functions, no useC + +of theiostream.h, I'll talk about this later. First, this is a continuous5Cycles to achieve5pause, wait for us to enter, we compile and run this program, assuming we enter separatelyABCDE, the result shown on the screen isABCDE, thisABCDEnot inCh=getch ();in the output, we putprintf ("%c", ch);This line of statement is removed and you will find that we press5The key program ends, but nothing is displayed on the screen.

Then we style= the getch () replace getche () Look what's different, We will also enter aabbccddee we put the printf ("%c", ch); This line of statement is removed and the result is abcde and the program executes the ch=getche (); This statement returns the key that we entered when it is displayed on the screen, with or without echo being the only difference between them.

Well, let's talk about why we don't use C + + libraries. You can try to change the program to C + + in the form of:

--------------------------------------

#include <iostream.h>

#include <conio.h>

void Main ()

{

Char ch;

for (int i=0;i<5;i++)

{

Ch=getch ();

cout<<ch;

}

}

--------------------------------------

You'll find that the running result is completely different, honestly I can't figure out how it was compiled and run, I used toC + +use it to implement any key continuation function to discover this problem. If thegetch ();There's one back .cout<< "...";statement, he will do the following first.cout<< "...";and then executegetch ();to achieve a pause, sometimes two statements in the Middle plus acout<<endl;can solve this problem, but if you useCin theprintf ()There has never been such a problem. As to exactly why, I do not know, can only conjecture, may be becausegetch ()is aCfunction in the library, and theC + +is not easy to use, that is, the problem of compiling the system itself, and we write the program does not matter. I do not know whether the analysis is correct, but also hope that the master can give advice, thank you!

Some people will say, since it is C 's function library, then it should be eliminated, we also study it, and use it to do? But I found that there is still a place to use it, otherwise I would not be here to say so much to delay everyone's time. Let me give an example, the program is as follows:

--------------------------------------

#include <stdio.h>

#include <conio.h>

void Main ()

{

Char ch= ' * ';

while (ch== ' * ')

{

printf ("\ n Press * to continue looping, press other keys to exit!) ");

Ch=getch ();

}

printf ("\ nthe exit program! ");

}

--------------------------------------

We can add the function we want in this loop body, the program press * continue to loop, the other keys to exit, and the use of getch () no echo of the characteristics, we no matter what, we do not leave traces on the screen, Make our interface beautiful, if there is a better way to achieve this function, I may not be here to mention so much. If you really have a better way, please be sure to tell me, thank you!

Here are some examples of other pages that I reproduced below:

--------------------------------------

Example One: This example is to illustrate the difference between getch () and Getche ()

#include <stdio.h>

#include <conio.h>

here is a small story: because this code is on someone else's web page, others use the C Environment, may not need to conio.h header file

You can use getch (); (I'm not sure), or I may have forgotten to write, the source code on the page is not #include <conio.h> this line,

I let my wife to see this webpage, the wife to copy the code on the webpage to C + + environment, cannot compile to cry with me,

Oh, my lovely silly wife!

void Main ()

{

char c, ch;

C=getch (); /* read a character from the keyboard without echoing to the character variable c*/

Putchar (c); /* Output the character * /

Ch=getche (); /* send a read-in character to the character variable from the keyboard ch*/

Putchar (CH);

printf ("\ n");

}

--------------------------------------

Example Two: This example shows the completion of the pause function during interactive input

#include <stdio.h>

#include <conio.h>

void Main ()

{

Char c, s[20];

printf ("Name:");

Gets (s);

printf ("Press any key to continue...\n\n");

Getch (); /* wait for any key to enter * /

printf ("\ n");

}

--------------------------------------

Example Three:thegetchar () function also reads a character from the keyboard and brings back the display. It differs from the previous two functions in that:

    the getchar () function waits for input until it ends with a carriage return, and all input characters before the carriage return are displayed on the screen one by one.

but only the first character is the return value of the function.

#include <stdio.h>

#include <conio.h>

void Main ()

{

char c;

C=getchar (); /* read characters from keyboard until end of carriage return * /

GetChar () Here it only returns the first character of your input string and assigns the return value to C

Putchar (c); /* Displays the first character of the input * /

printf ("\ n");

}

--------------------------------------

example four: Oh, this program you run a bit, I believe you will have doubts

#include <stdio.h>

#include <conio.h>

void Main ()

{

char c;

while ((C=getchar ()) = ' \ n ')//* each getchar () reads one character in turn * /

printf ("%c", c); /* Output as -is * /

printf ("\ n");

}

--------------------------------------

Example four of the program run, first stop, and so you enter a string, after the input is complete, it put you input the entire string is lost, gee, you do not say GetChar () only return the first word Fu Yi, here how?

Don't worry, I will explain to you slowly, patience, and immediately finished. Because we entered the string is not take the first character to throw away the rest of the string, it is in our memory, like, the opening of the water, we put in the brakes to go after, open a brake will be put off a point, open a little bit, until the light, we entered the string is such a thing, First we enter the string is placed in the memory buffer, we call once GetChar () in the buffer in the exit of the nearest character output, that is, the first character output, after the output, it was released, but there are strings behind, So we just use the loop to release the first character one after another in memory until the loop condition is not met. In the example, the "\ n" in the loop condition is actually the carriage return after you enter the string, so it means that the loop will not end until the carriage return is encountered, and GetChar () The function is to wait for input until it ends by pressing ENTER, so the output of the entire string is implemented. Of course, we can also change the loop condition, such as while ((C=getchar ())! = ' a '), what does it mean to encounter the character ' a ' to stop the loop.

C Language Getch (), Getche (), and GetChar ()

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.