473,750 Members | 2,265 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 #1
15 5757
Frank Bormann wrote:
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? [...]


There is no such thing as 'keyboard' AFA C++ _language_ is concerned.
Jul 23 '05 #2

"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:cZ******** ***********@new sread1.mlpsca01 .us.to.verio.ne t...
Frank Bormann wrote:
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? [...]


There is no such thing as 'keyboard' AFA C++ _language_ is concerned.


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.
Jul 23 '05 #3
Frank Bormann wrote:
"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:cZ******** ***********@new sread1.mlpsca01 .us.to.verio.ne t...
Frank Bormann wrote:
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? [...]


There is no such thing as 'keyboard' AFA C++ _language_ is concerned.

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.


Let me ask you, then. If 'in_avail' or 'readsome' returns 0, what makes
you think that "there's still input data present"? I mean, if you have
some other way of knowing that there are data in the stream, why don't
you use the same method to read it? Catch my drift?
Jul 23 '05 #4
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.

They are not part of the C++ standard though.
--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 23 '05 #5

"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:xC******** ***********@new sread1.mlpsca01 .us.to.verio.ne t...
Let me ask you, then. If 'in_avail' or 'readsome' returns 0, what makes
you think that "there's still input data present"? I mean, if you have
some other way of knowing that there are data in the stream, why don't
you use the same method to read it? Catch my drift?


There's still input data present, because get() or getline() reads it. My
problem currently is this:

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). If instead I use
"char c; cin.get(c);" and the user instead of just pressing <return> had
entered some other characters before pressing return, I read only the first
character and the others remain in the buffer. Now, the next time, program
flow comes across this "Press <return> to continue" code, the cin.get(c)
immediately reads the first of the characters that are still in the buffer
from the previous input. I can of course call
cin.ignore(nume ric_limits<stre amsize>::max()) ; as described in the C++ FAQ
to get rid of those characters, but if I do that and the buffer was already
empty, it never returns from the cin.ignore() call, no matter what I enter.
So I need to have a non-blocking way of knowing, if there are characters in
the cin buffer, so I can check before calling ignore.

Frank
Jul 23 '05 #6

"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.

Frank
Jul 23 '05 #7
Frank Bormann wrote:
[...]


You might want to consult the FAQ at:

http://www.parashift.com/c++-faq-lit...html#faq-15.17

HTH,
- J.
Jul 23 '05 #8
Frank Bormann wrote:

"Victor Bazarov" <v.********@com Acast.net> wrote in message
news:xC******** ***********@new sread1.mlpsca01 .us.to.verio.ne t...
Let me ask you, then. If 'in_avail' or 'readsome' returns 0, what makes
you think that "there's still input data present"? I mean, if you have
some other way of knowing that there are data in the stream, why don't
you use the same method to read it? Catch my drift?
There's still input data present, because get() or getline() reads it. My
problem currently is this:

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.

#include <string>
#include <iostream>

using namespace std;

int main()
{
string input;

cout << "Press <return> to continue\n";
getline( cin, input );

cout << "Bye\n";
}

waits exactly for the user pressing return.
Ok. The user can enter other things before the return, but
it definitly will return by just pressing the <return> key
If instead I use
"char c; cin.get(c);" and the user instead of just pressing <return> had
entered some other characters before pressing return, I read only the first
character and the others remain in the buffer. Now, the next time, program
flow comes across this "Press <return> to continue" code, the cin.get(c)
immediately reads the first of the characters that are still in the buffer
from the previous input.


OK. So what is hindering you to do:

char c;
while( cin.get(c) != '\n' )
;

That is: loop until the return key is detected?
You *know* that there has to be a '\n' somewhere.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 23 '05 #9
Frank Bormann wrote:

"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.


No.
As a rule of thumb: C++ knows nothing about any hardware. No keyboard, no mouse,
no monitor, no harddisk, no network, ...

Accessing such things is always platform dependent.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 23 '05 #10

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

Similar topics

3
2712
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
3701
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
3246
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
1919
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
2810
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
1334
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
1720
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
8838
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
9396
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...
1
9339
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9256
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8260
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...
0
6081
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
4887
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3322
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2804
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.