I was wondering, what the difference between these two functions is. I looked through the FAQ and couldn't find an explanation. I gather both read from stdin, so what's the difference?..
Greetz,
~Mako
I was wondering, what the difference between these two functions is. I looked through the FAQ and couldn't find an explanation. I gather both read from stdin, so what's the difference?..
Greetz,
~Mako
getch () is defined in conio.h which is non standard C, so some compilers won't have it, getchar () is in stdio.h.
they work differently too, getch wont display any text on screen - the moment you press a key it is entered - you don't press enter. a nice way of reading in a single character without needing to flush the input buffer afterwards.
No No's:
fflush (stdin); gets (); void main ();
Goodies:
Example of fgets (); The FAQ, C/C++ Reference
My Gear:
OS - Windows XP
IDE - MS Visual C++ 2008 Express Edition
ASCII stupid question, get a stupid ANSI
thx. As for getch being defined in conio, I can call it just by #include ing stdio....
as far as i know, if its in your stdio, then your compiler is including a non standard function - i've a similar case with Sleep and stlib.h. its a compiler specific thing, and normally getch should be in conio.
No No's:
fflush (stdin); gets (); void main ();
Goodies:
Example of fgets (); The FAQ, C/C++ Reference
My Gear:
OS - Windows XP
IDE - MS Visual C++ 2008 Express Edition
ASCII stupid question, get a stupid ANSI
Even thought getch is actually not in stdio.h, we can also use getch without including conio.h because C allows declaration-at-first-use of a function. That's, the first time you use a function, if you don't declare it before, you also declare it.
sorry about my poor English, hope you can understand me
Last edited by Antigloss; 01-24-2006 at 09:57 AM.
getch() is really handy for menu programs, like so:
That was a very simple example, but the best thing about it is that you don't have to press the enter key afterwards. I don't think it will work for strings.Code:char option; printf ("Press either A, B or C."); option = getch(); printf (" %d\n", option); switch (option) { case 'A': printf ("you pressed A!!"); break; case 'B': printf ("You pressed B"); break; case 'C': printf ("You pressed C"); break }
If you want to use it for numbers, I think you have to do something like this:
This works for me. The reason why you need the -'0' thing is because it stores the ASCII value of the number, which is the number itself PLUS the value of 0 ... know what I mean?Code:int number; printf ("Enter a number: "); number = getch()-'0';