0

I'm writing my first actual program in C++, and I'm just wondering why _getch() takes a few times to actually detect that I pressed a key. It'll usually take 2 or 3 tries before it actually picks it up and does what it's supposed to, and the first few times it just acts like nothing's happened. Here's all the relevant code:

#include <iostream>
#include <conio.h>

int main()
{
    using namespace std; // so i don't have to do 'std::cout' for every time I want to print, among other things
    cout << "Bag's Example Program\n\n";
    system("pause"); // waits for user input, with a "Press any key to continue" message
    bool chosen = false;
    while (chosen == false) {
        system("cls"); // clears the screen
        cout << "Enter a string: ";
        string words;
        cin >> words;
        cout << "You entered: " << words << "\n\nIs this correct? (Y/[N]): ";
        _getch(); // waits for user input
        if ((_getch() != 121) || (_getch() != 89)) { // if user's keystroke was NOT the 'y' key
            cout << "user selection was NO\n";
        }
        else { chosen = true; }
    }
}
hbag
  • 32
  • 6
  • note that `_getch()` actually is not C++. See here (but make sure to ignore the accepted answer): https://stackoverflow.com/a/1377453/4117728 – 463035818_is_not_an_ai Apr 22 '20 at 08:20
  • Oh, I know, I added a library that let me use it (I can't actually remember which one it was, it's late and I need sleep). That might be why, though. If all else fails, I'll try that. – hbag Apr 22 '20 at 08:22
  • 1
    you need to empty the buffer first. while (_kbhit()) _getch(); – AndersK Apr 22 '20 at 08:23
  • 1
    Please, note that `_getch(); if ((_getch() != 121)||(_getch() != 89))` might consume upto 3 characters from input. (Not to mention the bad habit of [Magic Numbers](https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants).) Maybe, this one is better: `int input = _getch(); if (input != 'y' && input != 'Y') {`... – Scheff's Cat Apr 22 '20 at 08:26
  • `cin >> words` may leave unconsumed characters in the internal input buffer. I suspect, at least, the characters to confirm your input with ENTER (`\r` or `\n` or even both) might be left. Hence, these characters are consumed immediately by the first following calls of `_getch()`. You can empty the input before with [`std::cin.ignore()`](https://stackoverflow.com/q/25475384/7478597). – Scheff's Cat Apr 22 '20 at 08:35

0 Answers0