Tuesday, July 14, 2009

In Linux c programming, can we read a single charecter into a char variable without pressing enter key ?

I wrote the following program but I have to press enter key to get read the value into the variable.


#include%26lt;stdio.h%26gt;


main()


{


char c;


while(c!='n')


{


scanf("%c",%26amp;c);


fflush(stdin);


printf("ok");


}


}


Is there any solution for this? Why?

In Linux c programming, can we read a single charecter into a char variable without pressing enter key ?
Use curses library. Its a wonderful library for exactly what you are looking for. Using this library you can handle keystrokes i.e. a char is trapped as soon as it is pressed, you dont have to wait for enter key press.





if curses.h is not availble in your machine, then re-run Linux setup, select custom libraries, there you will find ncurses library.





You get more info at:


http://www.gnu.org/software/ncurses/ncur...


http://www.unet.univie.ac.at/aix/aixprgg...


http://www.gmonline.demon.co.uk/cscene/C... -%26gt; great one to start off with





Good luck.
Reply:use the getch() function if you want to read a single char and not have it written to the console. If you want to read a char and have it written to the console then use getchar(). Neither function have any arguments to deal with and they only return characters from the keyboard, if either function returns zero it means that multiple keys have been pressed like Alt, if it dose return zero then you have to call the function again to find out what non-graphical keys were pressed. getch and getchar may not appear in your library of functions but it is in mine in the conio header.
Reply:Have you tried kbhit();


No comments:

Post a Comment