One character input is accepted without pressing the Enter key.

Source: Internet
Author: User

If you do not press enter, you will receive one character input!
Remember to write a log (http://blog.csdn.net/anyue417/archive/2006/08/14/1064145.aspx) a few days ago, such as the following program problems:
The Code is as follows:

# Include <stdio. h>

Void main ()
{
Int num = 0, Count = 0; // num obtains data from the keyboard. Count is used to record the number of cycles.
For (COUNT = 0; count <5; count ++) // loop 5 times
{
Num = getchar (); // input data from the keyboard
Printf ("% C", num );
}
}

It is true that it only runs three times, but it is not affected by any character or Integer type. I think each time I enter one character, I want to enter a carriage return to indicate the end of one input. If the input stream is used to press the carriage return, it is also considered a character. Then I forget it and add the carriage return five times, then I write the following code to test:

# Include <stdio. h>

Void main ()
{
Int num = 0, Count = 0; // num obtains data from the keyboard. Count is used to record the number of cycles.
For (COUNT = 0; count <5; count ++) // loop 5 times
{
Num = getchar (); // input data from the keyboard
If (num = '/N ')
{
Count --;
Continue;
}
Printf ("% C", num );
}
}

Today, when I read <C expert programming>, I found this section:
//////////////////////////////////////// //////////////////////////////////////// ////////
(Section 8.6) You do not need to press the Enter key to get a character

One of the first questions raised by MS-DOS programmers after switching to Unix systems is "How do I read a character from a terminal without pressing the Enter key ?" In UNIX, terminal input is "one pot" by default, that is, the entire line of input is processed together, so that the line edits the characters (backspace, delete, etc) it can be used without running programs. Generally, this is a convenient method that people want, but it also means that when reading data, you must press the Enter key to indicate that the input data can be obtained after the input row ends. This method is very effective for the entire line of input, but some programs need to get this character after each one-click, which is inconvenient.
This "one character input at a time" feature is very important for many types of software, but it is a piece of cake for PC. The C function library supports this feature. Generally, a kbhit () function is used. If a character is waiting to be read, a prompt is sent. The C compiler of Microsoft and Borland provides getch () (or getche (), which enables the character to be read and displayed on the screen at the same time) to obtain a single character, instead of waiting for the entire line to end.
People often wonder why ansi c does not define a standard function to get the character after a key. Since there is no standard method, every system uses a different method, which will lead to the loss of portability of the program. Those who oppose the inclusion of kbhit () in standards believe that it is used for gaming software in the vast majority of cases, and there are many other unstandardized terminal I/O features. In addition, you may not want a standard library function that is hard to implement in some operating systems. Those who agree with it believe that, in most cases, it is used in game software, and game writers do not need many standardized terminal I/O features. No matter which point of view you support, in fact the x3j11 team missed an opportunity to make C language a choice for a generation of student programmers to write games on Unix (that is, not absorbing this feature ). In UNIX, there are two methods to achieve character-by-Character Input, one is difficult and the other is easy. The easy way is to let the stty program implement this function. Although it is an indirect implementation method, it does not affect the program.

# Include <stdio. h>

Main ()
{
Int C;
/* The Terminal Driver is in the normal one-row mode */

System ("stty raw");/* put the Terminal Driver in One-Character Mode at a time */

C = getchar ();

System ("stty cooked");/* enables the Terminal Driver to return to one row */
}

The last line of system ("stty cooked"); is necessary because the state of the terminal character driving feature will continue after the program ends. After the Program sets the terminal as a funny State, if it is not modified, it will always be in this mode. This is obviously different from setting environment variables. The latter disappears automatically after the process ends.

You can set the I/O status to raw to implement blocking read. If the terminal has no character input, the process will wait until there is a character input. If non-blocking reading is required, you can use IOCTL () (I/O Control) System Call. It provides a good control layer for terminal features to tell you whether a key is pressed in the svr4 system. The following code uses IOCTL (), so that only one character can be read when it is waiting for the read process. This type of I/O is called polling. It is like constantly querying the device status to see if it has characters to pass to you.

# Include <sys/filio. h>
Int kbhit ()
{
Int I;
IOCTL (0, fionread, & I );
Return I;
}

Main ()
{
Int I = 0;
Int c = '';
System ("stty raw-echo ");
Printf ("Enter 'q' to quit:/N ");
For (; C! = 'Q'; I ++)
{
If (kbhit ())
{
C = getchar ();
Printf ("/n got % C, on iteration % d", C, I );
}
}
System ("stty cooked echo ");
}

//////////////////////////////////////// //////////////////////////////////////// //////////

I tested the above content one by one. The result is that the kbhit () function should be useless because it does not provide an input opportunity when using kbhit, it only checks whether there are any characters in the buffer zone. If a key is pressed, the corresponding key value is returned; otherwise, zero is returned. Return immediately regardless of the buttons. But how can this input be provided? It will not be used yet. While getch () and getche () provide an opportunity for input, but make the system in a "blocking wait state" (this should be said), the system keeps waiting for input, nothing else can be done. If you want to build a previously-used ping-pong program, it cannot be implemented. Another problem is that I did not find the above three functions in the Standard C language function library query manual.
But I can use them in vc6.0, but the warning is as follows during compilation:
Test. C (5): Warning c4013: 'kbhit' undefined; Assuming extern returning int
Test. C (10): Warning c4013: 'getch' undefined; Assuming extern returning int
I don't know why, but I just want to explain it to anyone.

The two methods proposed later are in Unix. I don't want to program in UNIX environment, so I will ignore them temporarily. Finally, the author mentioned the interruption. I think it is indeed a method. Of course, the higher level of implementation is multithreading. I won't do this now. If I use interruptions, I need to compile it. Well, I will do it later. But today we solved the problem that the last getchar () had to wait for the carriage return, because I used getch () in the initial code to replace getchar (), and the loop was five times, it is also a bit rewarding.

------------------------ All abve Based C -------------------------

Trackback: http://tb.blog.csdn.net/TrackBack.aspx? Postid = 1114543

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.