473,767 Members | 2,131 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to read a single keystroke in C++

Hi,

probably a stupid question, but I haven't been able to find anything.

Is there a istream related function that let me read exactly one keystroke
from the keyboard through cin?

What I need it to do is this:
- remove all characters currently in the input buffer
- block until the user presses a key
- return the ascii code of the key that was pressed

This should work also, if the user just hit the enter key.

I'm probably too stupid to get it right, but the usual get/getline()
functions always block until the user hits enter, even if the user enteres
other keys before, but on the other hand, if the user presses enter only,
getline continues to block and does not return the empty line.

Ideally I would like somethink like this:

1. a menu, where the user can press 1, 2 or 3 (and the program reactiving
immediately without the need for the user to press enter afterwards)
2. a "Press any key to continue" function, that waits for exactly one
keystroke, no matter what key it is.

Frank
Jul 23 '05
15 5758
Frank Bormann wrote:
Hi,

probably a stupid question, but I haven't been able to find anything.

Is there a istream related function that let me read exactly one keystroke
from the keyboard through cin?


Not a stupid question at all, because it's a tricky problem.

First, in_avail has always worked fine for me. I don't know why it wouldn't
work for you, so I can't help you there.

Second, cin calls blocking until enter is hit is not a problem of cin, but
of the OS. There are WinAPI calls (I don't know which exactly) that you can
use to set the console into return-after-each-character mode.

Third, I'm pretty sure - no, actually I *know*, because that very fact
caused me trouble just yesterday - that getline (at least the std::string
version) does not discard empty lines.

--
Sebastian Redl
Jul 23 '05 #11

"Karl Heinz Buchegger" <kb******@gasca d.at> wrote in message
news:42******** *******@gascad. at...
I want some "Press any key to continue" like implementation. Or at least
"Press <return> to continue" which would be less nice but still acceptable. Now, if I use cin.getline() to try and read such input, the cin.getline() call never returns, if the user just presses the <return> key (apparently because it's an empty line and getline discards that).


Aehm. Then you did something wrong.


Thank you!!! Yes, I was using the istream member function getline, not this
global string function.
This finally works at least for the "Press <return> to continue".

Frank
Jul 23 '05 #12
Frank Bormann skrev:
Hi,

probably a stupid question, but I haven't been able to find anything.

Is there a istream related function that let me read exactly one keystroke
from the keyboard through cin?

...
Frank


This is an OT-answer for Win32

_#include <stdlib.h>_

_system ("PAUSE");_

gives

"Press any key to continue"

Wasn't that what you were looking for?

-- Pelle
Jul 23 '05 #13
sam
Ioannis Vranos wrote:
Frank Bormann wrote:
Ok, let me ask differently: How can I determine, if there are chars to
read
in the cin streambuf without blocking? I've tried to use in_avail() and
readsome(), but they always return 0 on cin, even if there's still input
data present in the buffer.
I suppose in most PCs, cin accepts input only after you press Enter, so
the closest thing I can suggest is using the old, good, system-dependent
extensions, getch() and getche() (the second echoes the input). It is
usually defined in conio.h when it is available.

I never use this API in g++ before. Is it similar to curses base IO API?
In curses C API, it can do exactly what the OP is asking for.
Surely, you can "Wrap" curses C API into C++ classes. Perhaps curses has
already had a set of C++ API in the open source community.

Sam.
They are not part of the C++ standard though.

Jul 23 '05 #14

"Frank Bormann" <ne************ *@xoxy.net> wrote in message
news:42******** *************** @news.freenet.d e...

"Ioannis Vranos" <iv*@remove.thi s.grad.com> wrote in message
news:1113529832 .856545@athnrd0 2...
Frank Bormann wrote:

I suppose in most PCs, cin accepts input only after you press Enter, so

the closest thing
I can suggest is using the old, good, system-dependent extensions,
getch()

and getche()
(the second echoes the input). It is usually defined in conio.h when it
is

available.

I was afraid, you were going to say that. I was thinking about that too,
I'm
sure, I could easily manage to get what I want, by using the low-level
file
descriptor i/o of the glibc, but I was hoping to find a system-independent
solution.


The only way to do (almost) that is to specifically support certain known
platforms/implementations via conditional compilation:

#ifdef THIS_PATFORM
this_platform_g et();
#elseif THAT_PLATFORM
that_platform_g et();
#else
some_standard_b locking_input_f unction();
#endif

-Mike
Jul 23 '05 #15

"Sebastian Redl" <e0******@stude nt.tuwien.ac.at > wrote in message
news:42******** *************** @tunews.univie. ac.at...
Frank Bormann wrote:
Hi,

probably a stupid question, but I haven't been able to find anything.

Is there a istream related function that let me read exactly one
keystroke
from the keyboard through cin?


Not a stupid question at all, because it's a tricky problem.

First, in_avail has always worked fine for me. I don't know why it
wouldn't
work for you, so I can't help you there.

Second, cin calls blocking until enter is hit is not a problem of cin, but
of the OS. There are WinAPI calls (I don't know which exactly) that you
can
use to set the console into return-after-each-character mode.

Third, I'm pretty sure - no, actually I *know*, because that very fact
caused me trouble just yesterday - that getline (at least the std::string
version) does not discard empty lines.


<OT>
If you're using VC++ 6.0, note that the 'std::getline() ' supplied
with it has a bug which causes the behavior you describe, the fix to
which is available at http://www.dinkumware.com/vc_fixes.html
(One or more of the later VC++ 'service packs' from Microsoft might also
address this problem, I didn't check).
</OT>

-Mike
Jul 23 '05 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2714
by: Ste | last post by:
Hello, my goal would be implementing some keystroke analysis using php. I'm a novice in php, so i ask your advice: according to you, is it possible to log each keystroke client-side even if php is a server-side language, or shall i use JavaScript and make the client run the program locally? And, if i can use php to do that, how can i implement a feature logging keystrokes on the client system? Thanks,
7
6224
by: hokieghal99 | last post by:
Does anyone know of a keystroke logger that has been written in Python for Windows machines? I'd like to see such a script and use it as a point of reference for a real-time backup project that I'm working on. Basically, I'd like to be able to capture all keystrokes from the keyboard buffer and write them to a text file so I could reporduce emails, documents, etc. in the event of file loss that occurs between nightly backups. For example,...
7
3703
by: Brian | last post by:
Inside a loop, I need to passively check to see if a key is pressed or not without pausing like raw_input does. Some pseudocode: While true: If a key is pressed which key is pressed do other stuff inside loop
2
3247
by: Wayne Wengert | last post by:
I want to get the decimal (integer) value of user keystrokes. I am using the following code. chrInput is the character entered (e.g. "M") and "keystroke is DIMed as Short keystroke = Microsoft.VisualBasic.Val(chrInput) but it always yields a value of 0 How should I be doing this?
1
1922
by: Amin Gunawan via .NET 247 | last post by:
I would like to put a combo box in a column of a datagrid. I've seen the samples in the MSDN library of other sources, butall samples didn't catch the 'DOWN/UP' keystroke. It means thatwhen I select an item in the combo box, I need to use my mousefor the selection. If I use the 'DOWN/UP' keystroke, the cell inthe grid move to the next or prev row in the grid. Anybody knows how to catch the down/up keystroke when selectingitems in the combo...
10
2815
by: Martin Holm Pedersen | last post by:
Hey All.. Im having a bit of a problem with my program that i wrote for linux in c. I use select() to monitor if the user has pressed a key and reads the key with read(). It works fine om my IBM laptop but once i move the program to my dell laptop it seems like it doesn't even recognize the select-function. That is, it doesn't use the timeout assigned at all. I don't get any errors when i compile on either computer. I run debian/testing on...
2
1335
by: John | last post by:
We have an interesting programming problem and I wonder if anyone would know how to accomplish this, or be able to point me in the right direction I have a list of 100 items, in this case it's names and numbers. The entire list is written to one data grid, or table in an ASPX page As having to scroll through that list is already inefficient, and more names will be added, I need to find an elegant solution that will let me get to the...
1
1721
by: visweswaran2830 | last post by:
Hi, I need to stop the keystroke event when I pressed a particular key. For Eg: If press alt+tab key then that keys should not perform that operation, that should operation should be stopped. I captured that particular keystroke, but i want to knw how to stop that particular operation. Can any one help
0
9571
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9405
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10169
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10013
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8838
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7383
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6655
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5424
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2807
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.