getchar() is guaranteed to be defined in stdio.h in both ANSI C and ANSI
C++ (or cstdio in C++).
getch() is not guaranteed to be anywhere but usually happens to be
defined in conio.h .
getchar() is not similar to gets(), gets() reads C-strings and getchar()
one character.
getchar() returns int after the character is converted to int (unsigned
char->int).
getch() usually does the same thing.
Your code in a more portable & correct way:
#include <stdio.h> /* For printf() */
#include <conio.h>
int main(void)
{
char ch;
printf ("\nPress a key\n");
ch=getch(); /* Reads a character so ch is really
wasted space as an int*/
switch(ch) {
case 'a':
printf("You pressed the A key\n");
break;
case 'b':
printf("You pressed the B key\n");
break;
}
return 0;
}
Ioannis
* Ioannis Vranos
* Programming pages: <http://www.noicys.d2g.com/>
http://www.noicys.d2g.com
* Alternative URL: <http://run.to/noicys> http://run.to/noicys
-----Original Message-----
From: dev...@li...
[mailto:dev...@li...] On Behalf Of
Dan...@ao...
Sent: Sunday, January 20, 2002 9:11 PM
To: Dev...@li...
Subject: [Dev-C++] getchar(), getch(), getche()
Lets try to clear the air about getch() Vs getchar():
They are both prototyped in conio.h, this file is located in the DEV-
CPP\INCLUDE folder.
getchar() is similar to C's gets() in as much as the variable is
declared as a char. When event trapping if the programmer wants to use
numeric user input then he/she will have to convert it to an integer
using the atoi() function. Also when the user presses a key the have to
hit enter afterwards for the variable to read.
getch() is totally different in as much as the variable is declared as
an int so the program can read both Alpha and Numeric results without
any conversions to be done on the programmers end. Also the user just
has to type in the required key and it will be automatically inputted.
Here is a brief example:
#include <conio.h>
void main(void)
{
int ch;
printf ("%s", "Press a key\n");
ch=getch() \\this starts the event tripping procedures
switch(ch) { //this tells the program how to handle the user input
case 'a':
printf("%s", "You pressed the A key\n");
break;
case 'b':
printf("%s", "You pressed the B key\n);
break
}
}
The last function in this message concerns getche() which performs the
same as getch() with one exception and that is that when the user
presses a key the keystroke is echoed to the screen. This is great for
debugging a program.
In closing I'm working on a C tutorial that will include source code and
compiled examples. Any help with this project would be greatly
appreciated.
Danny
|