cin and getch()

C

Crow

Is there any way to make cin behave like getch()? Specifically,
getch() returns immediately after a key is pressed and the cin family
of input methods seem to block until a new line is encountered. I need
some help.
 
J

Jim Langston

Crow said:
Is there any way to make cin behave like getch()? Specifically,
getch() returns immediately after a key is pressed and the cin family
of input methods seem to block until a new line is encountered. I need
some help.

No.
 
D

Dietmar Kuehl

Crow said:
Is there any way to make cin behave like getch()?

Based on the standard, the answer is "no". The reason for this is
that the behavior of 'getch()' is not present on all systems where
'std::cin' still makes sense and there is actually nothing which
requires that 'std::cin' is connected to a keyboard at all. In fact,
it often isn't.

That said, on typical desktop systems there are calls which can be
used to suppress the usual line buffering mode. On a POSIX system
you can use 'tcgetattr()' and 'tcsetattr()' for this purpose. The
details of this are, however, not covered by the C++ standard and
you thus need to ask in an environment specific forum for a
solution.
 
N

n2xssvv g02gfr12930

Crow said:
Is there any way to make cin behave like getch()? Specifically,
getch() returns immediately after a key is pressed and the cin family
of input methods seem to block until a new line is encountered. I need
some help.

Look up the member function get() for std::istream derived classes. This
should do what you require in most cases. Alternatively you could create
your own version of getch() using std::cin, although I'd recommend you
learn to use the STL stream classes.

char ch;
std::cin.get(&ch);

JB
 
D

Dietmar Kuehl

n2xssvv said:
Look up the member function get() for std::istream derived classes. This
should do what you require in most cases.

Actually, it doesn't! 'get()' is mostly likely to block until input
becomes available and for input from the keyboard this normally means
until the user hits the return key.

If you want to use standard streams and still get the same behavior
like using 'getch()' you need to fallback to platform specific
approaches like using 'getch()' inside a stream buffer or setting up
standard input to not use line buffering mode.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top