Search code examples
cuser-inputkeypressfgets

Is it possible to capture Enter keypresses in C?


I want to write a C program that tokenizes a string and prints it out word by word, slowly, and I want it to simultaneously listen for the user pressing Enter, at which point they will be able to input data. Is this possible?


Solution

  • Update: see @modifiable-lvalue 's comment below for additional helpful information, e.g., using getchar() instead of getch(), if you go that route.


    Definitely possible. Just be aware that gets() may not be entirely helpful for this purpose, since gets() interprets enter not as enter per se, but as "now, I the user, have entered as much string as I want to". So the input gathered by gets() from pressing just an enter will appear as an empty string (which might be workable for you). See: http://www.cplusplus.com/reference/cstdio/gets/. But there are other reasons not to use gets()--it does not let you specify a maximum to read in, so it's easy to overflow whatever buffer you are using. A security and bug nightmare waiting to happen. So you want fgets(), which allows you to specify a maximum size to read in. fgets() will place a newline in the string when an enter is pressed. (BTW, props to @jazzbassrob on fgets()).

    You could also consider something like getch()--which really deals with individual key-presses (but it gets a bit complicated handling keys that have non-straightforward scan-codes). You may find this example helpful: http://www.daniweb.com/software-development/cpp/code/216732/reading-scan-codes-from-the-keyboard. But because of the scancodes issues, getch() is subject to platform details.

    So if you want a more portable approach, you may need to use something heavier weight, but fairly portable, such as ncurses.

    I suspect you can do what you want with either fgets(), keeping in mind that enter will give you a string with just a newline in it, or getch().

    I just wanted you to be aware of some of the implementation/platform issues that can arise.

    C can absolutely do this, but it's a little more complicated than one might guess at first attempt. That's because terminal input is, historically, very platform dependent.