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?

Answers


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.


Check out the conio.h library and its use in game making. You can compile with Borland. That was my first experience in unbuffered input and listening for keypresses in real time. There are certainly other ways though.


Need Your Help

Detail view on Map in Iphone SDK

iphone ios objective-c xcode mkmapview

In my app,I implemented a map View & added the annotations.

Sharepoint 2010 Replacable Parameter not working

sharepoint sharepoint-2010

I have an aspx page in _layouts that is part of a package. It contains :

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.