Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

maclover201

macrumors member
Original poster
Jul 4, 2007
46
0
I found some of this code on another forum but rewrote it so it's more versatile. A lot of people have been asking for a Unix/Mac equivalent, so here it is. :) Enjoy. Feel free to use it for anything you need.

getch.h:
Code:
(removed due to new version of getch.h)

main.cpp:
Code:
#include <iostream>
#include "getch.h"

using namespace std;

int main (int argc, char * const argv[]) {
	/*
            Example, updated for getch.h r2
	    Put only the characters you want getch to
	    wait for in the function parameter.
	    It will ignore anything other than those
	    characters and return which one was pressed.
       */
	cout << "Press A for apples, B for bananas, or C for carrots. ";
	char c = Terminal::Getch( "AaBbCc" );
	cout << endl;
	if( c == 'A' || c == 'a' )
		cout << "Apples" << endl;
	if( c == 'B' || c == 'b' )
		cout << "Bananas" << endl;
	if( c == 'C' || c == 'c' )
		cout << "Oranges. HA!" << endl;
	// Regular function example.
	// Terminal::Getch will wait for anything and return what character was pressed.
	cout << "Press any key. ";
	c = Terminal::Getch();
	cout << endl << "You pressed " << c << '.' << endl;
	// Sequential function example.
	// Terminal::GetSeq will wait for a sequence of characters.
	// If the wrong character was pressed, the user will
	// (unknowingly) have to enter the sequence over again.
	cout << "Find the sequence!" << endl;
	Terminal::GetSeq( "MacRumors" );
	cout << endl << "Well done! Also, you just lost The Game." << endl;
	return 0;
}

-Morgan [maclover201]

UPDATE: Please use getch.h r3 instead.
 

maclover201

macrumors member
Original poster
Jul 4, 2007
46
0
Update! Please use this version of getch.h as it is much less evil. The last version was really inefficient and would get terminal attributes every time it was called or would loop. The new one persistently stores this information in a class structure and only sets it once for the program's lifetime, so it's much better.

Here's how to upgrade your program to work with this version of getch.h:

-Change getch() to Terminal::Getch()
-Change getch(string) to Terminal::Getch(string)
-Change getch(const char *) to Terminal::Getch(const char *)
-Change getseq(string) to Terminal::GetSeq(string)
-Change getseq(const char *) to Terminal::GetSeq(const char *)

Pretty easy. It's really well-commented this time, so download, learn, and use! :D

-Morgan [maclover201]

UPDATE: Please use getch.h r3 instead.
 

maclover201

macrumors member
Original poster
Jul 4, 2007
46
0
Just noticed a glaring error that would affect some people compiling this code. Works the same as revision 2 though, so use it. Please. I beg you.

-Morgan [maclover201]
 

Attachments

  • getch_r3.h.zip
    1.9 KB · Views: 159
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.