Thread: Clearing the input buffer which doesn't have a newline

  1. #31
    Registered User
    Join Date
    Sep 2018
    Posts
    194
    I didn't know it worked that way.. interesting? (now pls don't say 'then don't guess' :'()

    Code looked like this:

    Code:
    char key
    while(run_time==1){
       key = getche();
       switch(key){
       case '1':
         sound(frequency 1);
         delay(10);
         nosound();
       case '2':
         sound(frequency 2);
         delay(10);
         nosound();
         break;
       default:
         run_time=0;
    }

    Do you reckon that I could use something like this:
    Code:
    sound(frequency);
    while(khbit()){
    delay(1); // is delay 1 too greedy? 
    }
    nosound();

    It makes sense now.. I got the small bursts of beeps because computers don't send infinitely quick inputs (thankfully, and I have no clue why I thought that..) and since getche() was reading only the input events it sent the beeps in small bursts.

    And that's why when we used longer delays (like half a second) we didn't have bursts of beeps (however the beep did last longer than the key press, which as explained by jim is because the key events were still being red by getche())

    Am I missing something? By the way 'delay(1);' sleeps for 1 millisecond.. so is that too greedy? Also wanted to add that when I used getche(); it didn't echo to the console. And according to my lab assistant getche() had to be used because getch() could not be used for input. My Cs teacher also said so. I tried this in only one lab session so I could not do my research and check in the compiler again.. but I know a lot more than I did for my next lab session thanks to you guys.. special thanks to jim and Salem my saviors.

    Thanks a lot you guys..


    You know what would be a nightmare? If Turbo C++ did not support khbit().. yeah.. let's not jinx it.
    Last edited by Nwb; 11-05-2018 at 11:54 AM.

  2. #32
    Registered User
    Join Date
    May 2010
    Posts
    4,446
    Am I missing something? By the way 'delay(1);' sleeps for 1 millisecond.. so is that too greedy?
    Too greedy for what? If you're talking about the second snippet why do you even need delay() at all? And by the way that while(kbhit()) probably should be while(!kbhit) so that if you hit a key the loop stops. And also note that kbhit() does not remove the character from the stream, it just detects the keyboard hit.

    Also wanted to add that when I used getche(); it didn't echo to the console.
    Then your console is broken, or you are mistaken. The getche() function in Turbo-C++ echos the character received, unlike getch() which doesn't echo the character.

    And according to my lab assistant getche() had to be used because getch() could not be used for input.
    Did you ask them why not? The getch() function in Turbo-C++ will retrieve one character from the console without echoing that character to the console. The getche() function retrieves one character from the console and echos that character to the console. They are basically the same the only difference is the echo behaviour.

  3. #33
    Registered User
    Join Date
    May 2010
    Posts
    4,446
    By the way here is the exact description of getch() from the Borland manual:

    Function getch() gets character from keyboard, does not echo to the screen.

    Remarks: getch reads a single character directly from the keyboard, without echoing to the screen.

    Return value: getch returns the character read from the keyboard.

    Now note that the documentation keeps mentioning "keyboard", not console. This is an important distinction.

    Function getche() gets character from the keyboard, echoes to screen.

    Remarks getche() reads a single character from the keyboard and echoes it to the current text window using direct video or BIOS.

    Return value: getche() returns the character read from the keyboard.

    Both of these functions have the following "warning": "This function should not be used in Win32s or Win32 GUI applications.". The reason for these warnings is because these functions were designed to directly access the hardware (keyboard, and display) which is not allowed under Windows.

  4. #34
    Registered User
    Join Date
    Sep 2018
    Posts
    194
    Code:
     char key;
    while(run_time==1){
    
       key = getche();
    
       switch(key){
    
       case '1':
           sound(frequency 1);
           while(khbit()) 
               delay(1);
           nosound() ;
    
    case '2':
           sound(frequency 2);
           while(khbit()) 
               delay(1);
           nosound() ;
    
       default:
         run_time=0;
    
    }
    Makes sense?

    Greedy because the while loop has to work so fast. Having no delay would take up an entire core of cpu so the delay is important.

  5. #35
    Registered User
    Join Date
    May 2010
    Posts
    4,446
    Greedy because the while loop has to work so fast. Having no delay would take up an entire core of cpu so the delay is important.
    What? Do you think you're still operating on a single threaded operating system? Modern Windows can and does preempt regularly operating programs to preform normal housekeeping and allow other processes to have opportunities to execute. If you're going to worry about taking up time then you shouldn't be using these DOS functions, that assume that they have direct and sole access to the hardware, and start learning the Windows API functions that replace these functions.

  6. #36
    Registered User
    Join Date
    Sep 2018
    Posts
    194
    An infinite while loop takes 25% of my cpu. Add a delay and that usage is gone to almost nothing..

  7. #37
    Registered User
    Join Date
    May 2010
    Posts
    4,446
    An infinite while loop takes 25% of my cpu.
    So what? If you had other things really working the percentage would probably decline dramatically.

  8. #38
    Registered User
    Join Date
    Sep 2018
    Posts
    194
    There's no difference in output in both cases when there is delay and when there is not. If you can bring down cpu usage isn't that a better option then?

  9. #39
    Registered User
    Join Date
    Sep 2018
    Posts
    194
    It returns a non-zero integer if a key is in the keyboard buffer. It will not wait for a key to be pressed.
    khbit() reads from the keyboard buffer.. does that mean it won't read key down events and like getch() will only read key events? :'(?

    Seems I can use
    Code:
    while(kbhit()) getch();
    to clear the keyboard buffer.
    So I have two options depending on how khbit() responds.


    Code:
    char key;
    while(run_time==1){
     
         while(kbhit()) 
              getch();
    
       key = getche();
     
       switch(key){
     
       case '1':
           sound(frequency 1);
           while(khbit()) 
               delay(1);
           nosound() ;
     
       case '2':
    
           sound(frequency 2);
           while(khbit()) 
               delay(1);
           nosound() ;
     
       default:
         run_time=0;
     
    }
    or
    Code:
    char key;
    while(run_time==1){
    i++;
     
       key = getche();
     
       switch(key){
     
       case '1':
    
           sound(frequency 1);
    
           delay(250);
    
           nosound() ;
     
       case '2':
    
           sound(frequency 2);
    
           delay(250);
    
           nosound() ;
     
       default:
         run_time=0;
     
    }
    In VS compiler, the second approach works fine, the first doesn't. In the first approach it starts sound but never stops..

    code I ran:
    Code:
    #include <iostream>
    #include <conio.h>
    #include <windows.h>
    
    using namespace std;
    
    bool run_time = 1;
    int i = 0;
    
    char key;
    
    int main() {
    
    
        while (run_time == 1) {
    
            while (_kbhit())
                _getch();
    
            key = _getch();
    
            switch (key) {
    
            case '1':
                cout << "\non" << i;
                while (_kbhit()) {
                    Sleep(1);
                }
    
                cout << "\noff";
    
    
            default:
                break;
    
            }
        }
    
        system("pause");
    }
    Why this behavior? It's as if the _kbhit() is true even when the user is not clicking a key..
    I tried replacing
    Code:
                while (_kbhit()) {
                    Sleep(1);
                }
    with
    Code:
                while (_kbhit()) {
                    Sleep(1);
                    _getch();
                }
    But that just made it so that the loop is broken even when the user is holding a key..
    Last edited by Nwb; 11-06-2018 at 02:59 AM.

  10. #40
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,485
    > An infinite while loop takes 25% of my cpu.
    It takes 100% of 1 core of your 4-core machine.

    Which is another reason (to the long long list of reasons) why you shouldn't be using that PoS.
    - It cannot use more than 1 core of your machine
    - It only knows how to do 16-bit arithmetic (most machines from the last few years are up to 64-bit now)
    - It can only access a maximum of 640KB (yes, really, KILOBYTES FFS). How many GB do you have?
    -- Worse than that, it's all broken up into tiny 64KB segments, so writing anything with large data is a real PITA.
    - It only knows about 8.3 filenames.
    - It only knows about FAT filesystem.
    - It doesn't know that Y2K is a thing (that was 20 years ago).
    - It doesn't do threads, networking, and a whole bunch more.
    - The graphics is does have are laughable by today's standards (640x480x256 colours - if you're lucky). How does that compare to your actual screen resolution?
    - You're stuck with the meagre API (so no goodies in windows.h for you).

    Seriously, no one would try to run the WWW if your web server is the Gutenberg printing press.

    Which version of Windows are you using - XP / Win7?
    Anything later, and you need DOSBox, an x86 emulator with DOS just to get anything DOSsy to run at all.



    Try this, and watch the scroll-fest.
    Code:
    while ( 1 ) {
        if ( kbhit() ) {
            int ch = getch();
            printf("Key %d(%c) pressed\n",ch,ch);
        } else {
            printf("No key pressed\n");
        }
    }
    Tap a key, hold a key down, see what happens.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  11. #41
    Registered User
    Join Date
    Sep 2018
    Posts
    194
    I don't know what PoS stands for but I assume you're talking about Turbo C..
    Salem Salem.. for gods sake I am not planning on downloading Turbo C++ for myself or think it's great.

    I was talking about infinite while loops and any compiler would cause such a loop to take an entire processor (try it). Because you're not instructing the compiler how quick it must work. I was just saying that it's a bad programming practice to have infinite while loops when you can afford to have a delay of 1 millisecond (no keyboard is precise to the millisecond anyway so it's not like you're losing anything).

    While loops that actually calculate something are fine, but while loops that keep checking for a value do not need to work 100000000000 iterations per millisecond. Like the while loop I was using in my case, it unnecessarily works so many iterations while my keyboard itself might not be precise to 100 milliseconds.

    On the other hand if you just added a delay of 1 millisecond you get 0% CPU usage. 0 is far better than 25%.

    I couldn't edit my previous reply I donno why but regarding to kbhit() it all makes sense now.
    kbhit() reads from the keyboard buffer so just like getch() it sees keyboard events and not key downs. However unlike getch() kbhit() does not remove the character it reads from the keyboard buffer. This is applicable to the function's counterparts in VS.
    Last edited by Nwb; 11-06-2018 at 04:51 AM.

  12. #42
    Registered User
    Join Date
    May 2010
    Posts
    4,446
    but regarding to kbhit() it all makes sense now.
    I don't really think you do.

    kbhit() reads from the keyboard buffer so just like getch()
    No, neither of these function read from any buffer. They interact "directly" with the hardware, no buffering!

    it sees keyboard events and not key downs.
    The only "events" these three functions detect are key down "events" they don't react to any other keyboard "event".

    However unlike getch() kbhit() does not remove the character it reads from the keyboard buffer.
    All the kbhit() function does is detect if a key has been pressed, it doesn't read anything.

    This is applicable to the function's counterparts in VS.
    Not necessarily, these functions are implementation defined and can differ greatly as to how they are implemented. Don't confuse yourself by insisting that both implementations do the same things. And don't forget that there are other implementations of these functions available for other DOS/Windows based systems that may or may not work the same.

    Well enough time wasted on a dinosaur, good luck. You really need to forget about these ancient functions that can no longer really do what they were designed for since they no longer can access real hardware on current operating systems.

  13. #43
    Registered User
    Join Date
    Sep 2018
    Posts
    194
    Jim a function that can check if a key was pressed and a function which can check if a key is being pressed down are different. I tend to refer to them as 'key events' and 'key down events'. I think we have established that C++ cannot check for 'key down events' without using some library or win api, which is great that's one more thing I learnt here.

    So yes kbhit() checks if there is something in the keyboard stream, and we can use this fact to clear out unwanted key events by using the while loop I mentioned.

    Granted that VS's implementation for these functions is different, but I'm sure they were intending on having the same functionality. I just mentioned that for the fact that VS users can use these functions also, but of course nobody should, but they can. Except for the weirdness of _getch() the functions are pretty similar in functioning.

    Time wasted on a dinosaur? Yes indeed. But a lot more time spent doing something useful because of this. I am going to be spending a lot of time these 2 years sitting in front of that Turbo C++ compiler. Either I can write my record (which I much prefer doing while listening to music at home) or I can work on the system. With these conio.h functions I can do all sort of amazing stuff, for instance I can make a tic-tac-toe game (which you could do with iostream too) but more importantly I can try making games like snake, spaceship and a piano simulator (okay okay it's not really a piano it's a button-click-and-noise device) like mentioned here.

    clrscr(); kbhit(); getch(); and ASCII characters (I use (char)219 for filling the console) are really all you need. Me iz happy.

  14. #44
    Registered User
    Join Date
    May 2010
    Posts
    4,446
    I think we have established that C++ cannot check for 'key down events'
    Says who?

    without using some library
    And what do you think the conio.h provides an interface for? Perhaps a library?

    which is great that's one more thing I learnt here.
    No you really haven't learned anything. You just think you have.

    clrscr(); kbhit(); getch(); and ASCII characters (I use (char)219 for filling the console) are really all you need.
    So you think char 219 is ASCII? Another thing you haven't learned.

    Good luck.

  15. #45
    Registered User
    Join Date
    Sep 2018
    Posts
    194
    So you think char 219 is ASCII? Another thing you haven't learned.
    219 of the ASCII table is AN ASCII character that represents a white block like symbol, are you happy? I'm not a perfectionist but I thought you'd have understood at least what I meant.

    And what do you think the conio.h provides an interface for? Perhaps a library?
    There's difference between having to add files and not having to add files.

    No you really haven't learned anything. You just think you have.
    How do you know that? Are you secretly keeping track of what's happening in my brain?

    Says who?
    Prove me wrong then. "Says who" isn't a valid argument.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Using getchar() to flush newline from input buffer
    By Valour549 in forum C Programming
    Replies: 15
    Last Post: 11-03-2018, 07:49 AM
  2. Clearing c++ input buffer
    By mramazing in forum C++ Programming
    Replies: 4
    Last Post: 11-08-2007, 11:05 AM
  3. clearing the buffer - but not the newline
    By Ash1981 in forum C Programming
    Replies: 13
    Last Post: 01-06-2006, 05:22 AM
  4. Clearing the input buffer
    By caduardo21 in forum C Programming
    Replies: 1
    Last Post: 05-14-2005, 08:40 PM
  5. Clearing the Input buffer
    By Brain Cell in forum C Programming
    Replies: 5
    Last Post: 03-21-2004, 12:08 PM

Tags for this Thread