i just want to whether there is a replacement for getch() in C++.

my friend said getch() is C function.

thanks!

Recommended Answers

All 37 Replies

>i just want to whether there is a replacement for getch() in C++.
There isn't a standard equivalent for getch in either C or C++.

>my friend said getch() is C function.
No, getch is a compiler extension. You can use it in either C or C++ if your compiler supports it, but for the most part you don't need to.

For what purpose were you intending to use getch? The most common by far is keeping a console window from closing when you run the program from a Windows IDE:

#include <conio.h>

int main()
{
  // Your program here

  getch();
}

That's not a recommended solution, and most experienced programmers will recommend that you use cin.get:

#include <iostream>

int main()
{
  // Your program here

  std::cin.get();
}

Okay, I have to say that i often use getch() not just to halt the console window.
I used getch() along with kbhit() [to get the key if pressed any]--very important use of getch().
And there are times when I have given the user to choose from a number of options (menu items) and used getch() to get the choice. I know the latter can be done with any input functions but getch() makes it simpler-- scanf(), cin and cin.get() will show the keys as u type in and then u have to press enter, whereas in getch() u just press the key and it's not even shown. getch() also makes things easier as u can enter only one key and there's no chance of receiving any degenerate inputs. On the otherhand it's very common for scanf(), cin and cin.get() to mess up with the inputs when only one keystroke is sufficient and desireable.

i would really love to know if there's any other way to get the functionality of getch()(i.e without using getch()) in the above mentioned cases.

i'm using getch() at password entering that display * when password is entered.

i'm using getch() at password entering that display * when password is entered.

yes, i have used it for the same purpose for one of my programs too. I hope some one here will suggest how to work that out without using getch(), since according to "Narue" its a compiler extension and not a C function. Now we dont to code using something that is not part of the language.

i would really love to know if there's any other way to get the functionality of getch()(i.e without using getch()) in the above mentioned cases.

The problem with unbuffered input is that it becomes the responsibility of the programmer to handle the buffering. Do you allow the user to make a typing mistake? Then handle the backspace. Then you can't have immediate response because you need an "enter" for a 'final' answer. Then you're back where you started with the standard way.

The reason it may 'work well' might be because other issues have been overlooked. It seems a more reasonable approach is to use standard functions that have already taken such issues into account and move forward. Yet this opinion is revisited thousands of times every year by programmers. Their first goal seems to be clearing the screen. Frankly, if the command shell commands behaved this way, I'd be pretty annoyed: execute two 'dir' commands consecutively, and the second throws away the result of the first -- annoying.

Ah well, it seems new programmers always must go full circle. I do try to get them to go the right way first, otherwise it seems to be a much longer journey.

That said, any nonstandard function has the implied disclaimer, "use at your own risk"! :p

commented: Absolutely my thoughts :) +2

Try
#include <iostream.h>
void main()
{ ...... /* your program here */
cin.get();
}

It should work .

>It should work
No, it should do whatever the hell it wants because you've invoked undefined behavior. And even when the undefined behavior is something intelligent, iostream.h is a nonstandard header, so you can't be sure that cin.get() even exists, much less that it does what you want it to.

To anyone reading this thread:
getch() is still available in the conio.h header file (at least in MinGW). cin.get() acts the same as getchar() - it echos the pressed key and waits for enter to be pressed.

And don't worry, Narue is wrong - iostream is very standard for C++.

commented: Learn before you teach. -2

>To anyone reading this thread:
You realize the thread is over three years old, yes?

>getch() is still available in the conio.h header file (at least in MinGW).
I'm sure it works just fine on your compiler, but because it's non-standard, that means it's not guaranteed to work on my compiler, or someone else's compiler. Is this that difficult of a concept for you people to grasp?

>cin.get() acts the same as getchar() - it echos the
>pressed key and waits for enter to be pressed.
Assuming that's what getchar does. getchar makes a call to a system function that performs the actual read, and that system function (whatever it may be) isn't required by the C++ standard to provide cooked input. However, I'll give this to you because I can't think of any systems off the top of my head that don't buffer up to a line feed. It's a safe assumption.

>And don't worry, Narue is wrong
Narue is always right[1]. You'd do well to realize that before truly embarrassing yourself.

>iostream is very standard for C++.
<iostream> is standard, <iostream.h> is not. Once again, this is a very simple concept, but I'll assume that you're just having trouble with reading for comprehension and missed the ".h" part.


[1] I'll qualify this. Narue is always right when it comes to the likes of you. I do make mistakes, but I get the strong impression that you're not a strong enough programmer to notice them or accurately correct me even if you do.

commented: Narue IS always right, from my experience ;) +4

1) Yes, I realize that. i just thought I'd post it here for anyone who stumbles across it as I did.

2) It's not that hard for me to understand, and that's why I added the condition "in MinGW". The MinGW compiler supports getch, so anyone using a MinGW compiler will be able to compile the code. After it's been compiled, running the program on the intended platform should have the expected results.

Also, as Cygwin installations typically include MinGW libraries, Cygwin also supports the conio functions like getch. And MS Visual C++ also has the conio library. What compilers don't support it?

3) I'm explaining that cin.get() is not a suitable replacement for getch() for the applications given above.

4) Okay, you got me there. I believe that the ".h" version was the one used before streams became standard (in Borland). Anyway, that's being nit-picky as it was probably just a typo, and anyone would very quickly discover that the ".h" is not needed (since that version isn't included in the installs anymore).

>i just thought I'd post it here for anyone who stumbles across it as I did.
It's generally considered rude to resurrect ancient threads, for any reason.

>The MinGW compiler supports getch, so anyone using a <blah blah>
Okay, point out on this thread where you're not the first person to mention a specific compiler or OS. I can describe situations that only work on a PDP-11, and they'd be just as completely irrelevant as you talking about MinGW on this thread. getch is non-portable. That was already mentioned, so you don't have to list the compilers where it does and doesn't work. That's what the manual is for.

>I'm explaining that cin.get() is not a suitable replacement for getch() for the applications given above.
For the application I mentioned it's a perfectly suitable replacement. For masking a password, it's not, but because the OP was okay with using getch after finding out that it's neither C nor C++, but a compiler extension, no replacement was necessary.

>I believe that the ".h" version was the one used before streams became standard
Correct.

>Anyway, that's being nit-picky as it was probably just a typo
I seriously doubt that it was a typo. A lot of newbies use compilers that take pre-standard code. The lack of namespaces and the use of void main makes it extremely likely that iostream.h was meant.

#include <iostream>

using namespace std;
void main(){
cout << "hit any key";
cin.get(); // waiting for any input
}

cin.get(); or std::cin.get(); if we don't using namespace
all works fine.

>void main(){
main returns int. Since you can omit the return statement in C++, using int main on top of being correct and portable actually saves you one keystroke. It's a win-win situation. :)

getch() is also actually available in C++ while it's a compiler extension it might not be available with your compiler etc.
for example if you're using Microsoft VC++ 2005 or later you may find these two functions useful :

int _getch( void );
wint_t _getwch( void );

these methods are locking and thread-safe, non-locking versions of these two functions are available as _getch_nolock and _getwch_nolock !

--
Good Luck !
The dNetGuru

>To anyone reading this thread:
You realize the thread is over three years old, yes?

>getch() is still available in the conio.h header file (at least in MinGW).
I'm sure it works just fine on your compiler, but because it's non-standard, that means it's not guaranteed to work on my compiler, or someone else's compiler. Is this that difficult of a concept for you people to grasp?

Found this thread when googling getch, and I had to respond.

The function you're discussing is NOT a "compiler extension". It's a library function. Crap like this is why people think that C/C++ is so difficult. There is a difference between a language feature and a library function. Jesus, learn the language, people!

The C++ Standard Library is not C++! Console I/O functions are not part of the compiler! You can use any library function with any compiler, as long as you compile the library source using your compiler.

Goddamn...No wonder there are so many idiot java programmers.

commented: stop the cursing. -7

You have always the choice cause it C++

it just direct track of the keyboard using terminal for linux

just add its segment all will work fine..

like clrscr() also does not work for that is you can use the system() function and type the console command

In the program i have define it as "cls" so you can use it directly... as cls ; in the program

If you remove the #define Linux the code will include the Conio and you can use the getch() in any case ...
Just you any old program in windows can run fine now. .if you add this snippet above the code

#include<iostream>

using namespace std;

#define Linux //Remove this for running in windows

#ifdef Linux
	#define cls system("clear")	
	
	#include <termios.h>
	#include <unistd.h>

	int getch();
	int getch()

	{

		struct termios oldt, newt;
		int ch;
		tcgetattr(STDIN_FILENO, &oldt);
		newt= oldt;

		newt.c_lflag &= ~(ICANON| ECHO);
		tcsetattr(STDIN_FILENO, TCSANOW, &newt);
		ch= getchar();
		tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

		return ch;
	}
#else
	#include<conio.h>
	#define cls system("cls")
#endif

#include<stdio.h>


..
..

int main()
{
 ..
 .. 
return 0;
}

>Found this thread when googling getch, and I had to respond.
I recommend you resist that temptation next time. Posers should know their limits.

>The function you're discussing is NOT a "compiler extension". It's a library function.
If you want to split hairs with terminology, it's a library extension. But whatever you call it, the result is the same: the function is not portable. Calling it a compiler extension is more productive as most beginners can't differentiate between the compiler proper and the libraries. If I say it's a library extension, that will encourage more questions like "I want to use graphics.h with <a compiler it wasn't designed for>".

>The C++ Standard Library is not C++!
That's not quite true. C++ is defined by the C++ standard, and you'll find sections on the standard library in that document. If a compiler package doesn't include the standard library, it doesn't conform to standard C++.

>You can use any library function with any compiler, as long
>as you compile the library source using your compiler.
Perhaps you should try to understand what you're talking about before being a jerk about it. The vendor-provided libraries for a compiler are already compiled. Sometimes vendors provide source code for the libraries, sometimes not. This results in two problems, which are more pronounced in non-portable functions like getch:

1) If you have the source code, chances are extremely good that it uses features, libraries, or APIs that are specific to either the compiler or the platform the compiler is targeted for. Unless you remove those non-portable parts, you can't use "any library function with any compiler, as long as you compile the library source using your compiler". You ultimately have to port the function to the compiler you want to use it with, which could involve a lot more work than simply recompiling.

2) If you don't have the source code, you only have a binary version of the library and thus have to disassemble and reverse engineer the functions you want before you can get to the point of compiling with another compiler. Of course, you still have to handle the first problem after you've done all of this grunt work.

>Goddamn...No wonder there are so many idiot java programmers.
You don't know what you're talking about. A little book knowledge, a pedantic attitude, and arrogance aren't going to hide that from people who do know what they're talking about.

The good news is that posers can become actual authorities on a subject. Keep trying, one day you might actually be able to debate intelligently with me.

commented: Eloquent as ever :) +22

Narue: "Posers should know their limits."
You say it's rude to resurrect old threads but you're rude whenever you feel like it. One of the rules of this forum is "keep it pleasant". You are not following that rule. It's sad how a relatively simple skill like programming can go to a simpleton's head. Don't bother to respond; I won't read it.

commented: I will say Nature is extremly kind to answer some stupid debates and was not rude in that post. Inspite of those harsh words by the prevoius poster Nature replied politely. +0

>but you're rude whenever you feel like it
I'm appropriately rude. If you're rude to me, don't expect me to be nice to you.

>One of the rules of this forum is "keep it pleasant".
Not only am I quite familiar with the rules, I'm in the unique position of having the final say on their interpretation.

>You are not following that rule.
The key phrase in Keep It Pleasant is "malicious intent", which is the deciding factor in enforcing this rule. If it's determined that there's no malicious intent, even rude posts are more likely to be allowed than not. As such, I don't feel I've broken that particular rule. However, as it appears you've reported my post, I'll step aside and allow the rest of the mod team make an objective decision. Thank you, by the way, for reporting posts you feel cross the line regardless of who the author is. Nobody is exempt from following the rules.

>It's sad how a relatively simple skill like programming can go to a simpleton's head.
If you think programming is simple, you clearly haven't done much of it.

>Don't bother to respond; I won't read it.
I don't believe that for one second. If you're egotistical enough to scold me for not being nice when it has nothing to do with you, you're egotistical enough to be interested in my reply.

To be honest, I was half expecting your IP to match nomorejunkmail's. :D

Found this thread when googling getch, and I had to respond.

Ditto.

getch() is deprecated. Instead, MS recommends you use _getch() (note the underscore) Same with kbhit() - use _kbhit() instead.

Personally, I find _kbhit() more useful, because _getch() will block waiting for input and if I wanted to block I'd use cin instead. _getch() also locks the current thread by default (_kbhit() doesn't need to since it's just peeking at the buffer); there are non-locking versions, e.g. _getch_nolock()

Include conio.h if you wish to compile code with _getch().

Also, make sure you link against the C Runtime (CRT) library. _getch() is a part of the CRT. Typically, the CRT is provided in pre-compiled object form (*.lib) by whoever wrote your compiler (e.g. Microsoft if you're using Visual Studio). It's usually linked in by default, but you may need to instruct your linker to link against the library, typically libcmt.lib or libcmtd.lib. (libcmtd = LIBrary C MultiThreaded Debug)

@guru_boy:

It's generally considered rude to resurrect ancient threads, for any reason.

You didn't bother reading the thread before posting eh?

on my entire online life, this is the most bizarre thread i found. the thread started Oct 3, 2004.

got an unexpected resurrection 3 years after. and another year it was resurrected with some arrogance and rudeness and on the next year it was resurrected again. can anyone lock this thread and create a new one if the case was not yet solved. it was almost 5 years since the thread was started.

and a side about the compiler and libraries. frankly.. there are a lot of new programmers which cannot differentiate a pseudo code from an actual live source code. let alone to know the difference from extended libraries and extended compiler features.

cya for now.. i'll continue my search for methods to emulate getch.

commented: And you just had to join and add your $0.0000000002 worth right? -7
commented: Thread tools -> Unsubscribe from this thread -4

on my entire online life, this is the most bizarre thread i found. the thread started Oct 3, 2004.

I know it's difficult to comprehend, but sometimes programming languages and their associated APIs evolve. This page was a rather prominent result during my google search for getch and it suggests using deprecated features. To me, it was just common sense to add some information for future googlers who stumble on this thread.

and a side about the compiler and libraries. frankly.. there are a lot of new programmers which cannot differentiate a pseudo code from an actual live source code. let alone to know the difference from extended libraries and extended compiler features.

And maybe some of those new programmers will google terms I used that they do not understand, and maybe they'll even learn enough to stop being "new programmers".

commented: You didn't help either -7

I'm looking for a way to grab a single character from the console without the need to hit "ENTER" after each character. I know that getch() has this feature and cin.get() does not. Is there a 'better' method than getch() to grab a single console character without the "ENTER"?

Thank you.

Member Avatar for iamthwee

I'm looking for a way to grab a single character from the console without the need to hit "ENTER" after each character. I know that getch() has this feature and cin.get() does not. Is there a 'better' method than getch() to grab a single console character without the "ENTER"?

Thank you.

If it works, it works.

There's no point worrying about if a better methods exists because getch() or anything that simulates its behaviour is going to be non-standard anyway, so your concern is a moot point.

As far as i know getch() is deprecated and it was replaced. TurboC++ users miss getch() a lot.

I used google trying to find what is the easy way to implement the ubiquitous "Hit any key to continue." in a "console" app (I'm using Visual Studio 2010 atm).

I found the answer above, thank you DCX2. Here is the 2010 version of the answer:

http://msdn.microsoft.com/en-us/library/58w7c94c.aspx

Microsoft: "Use the ISO C++ conformant _kbhit"

(You have do do something like:

while( !_kbhit() );

)

[o.t. rant]
Since this thread has already been thoroughly trashed by people more concerned with showing how much smarter they are than the other poster [implicitly bringing themselves down to their level] I must address a particularly irksome point:

> "It's generally considered rude to resurrect ancient threads, for any reason."

NO! To anyone who says that, please stop it already!!!

I have been reading the Internet since about 1987. That general idea about posting to "old" threads being bad has to be one of the most ignorant ones I have run across in twenty five years... Ugh.
[/o.t. rant]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.