How can I read one character from the console?
For example: "Are you sure? (D) a, (H) et."
It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reasons:
Nostradamlyu :) that before this somewhere there was a read in the spirit of scanf("%d" without a reset after this input buffer, so \n remains in it, which is read by the next scanf .
Check if you reset the buffer ( fflush nothing to do with it, if that), and if not, try resetting ...
Well, the second option is the wrong encoding, if you are reading Russian characters ...
On the advice of @AndrejLevkovitch: resetting the buffer means taking the rest of the line to nowhere :) - for example,
for(int c = getchar (); c != '\n' && c != EOF; c = getchar ()); Typically, keyboard input comes line by line into the program. In C, there is no standard portable way to read a single character from the console, without waiting for the Enter key. comp.lang.c FAQ: How can I use the RETURN key?
In other words: getchar() will not return until '\n' is encountered (which can happen after entering many many characters). In order not to wait for a new line to read a single character from the Windows console, you can _getche() / _getwche() from conio.h .
On Unix, you need to change the terminal mode in order to get character input and restore the previous settings on your own when you exit the program. For example, using the curses library, you can cbreak mode :
#include <ctype.h> #include <curses.h> int main() { initscr(); cbreak(); // change terminal mode to accept a char at a time // get answer int c; do { mvaddstr(0, 0, "Are you sure? (Y)es/(N)o: "); c = getch(); c = toupper((unsigned char)c); } while (c != 'Y' && c != 'N'); endwin(); // restore terminal settings return c == 'N'; } Example:
$ cc *.c -lcurses && ./a.out && echo yes || echo no Let's say you need to find out the confirmation from the user and write to the variable for this purpose the function scanf(); and learn how to work with MANAGER SEQUENCE scanf ("%c",&i); writes one character to the variable i and here% s already several characters. To be sure, you can loop this into validating the data entered.
do {scanf ("%c",&i);}while (!(i == 'Y')||(i == 'N')); Source: https://ru.stackoverflow.com/questions/765143/
All Articles