KEY_ENTER vs '\n'? - c++

When I'm using PDcurses and I try to have a while loop exit when the enter key is pressed with while(key != KEY_ENTER), the while loop never exits. However, when I try to have the same loop exit with while((char)key != '\n'), it exits successfully whenever I pressed enter. Why does '\n' work and not KEY_ENTER?
btw, key is an int
and I hope this is the relevant few lines of the code:
int key;
while((char)key != '\n') {
key = getch();
...
}

getch() is a function defined by the ANSI C standard for the C runtime library.
On most systems, such as Windows, Linux, etc., this function is implemented to return '\n' when the user pressed Enter. For Comparison, on Windows the key-press itself (of Enter) might be represented as the key-code VK_ENTER.
PDCurses is translating the key codes to ASCII values for you.
You can get the key values you want if you first call the PDCurses functions raw(); nonl();. Also, you should probably use wgetch() for new code.

KEY_ENTER == 0x157, '\n' == 0xA
'\n' is the standard ASCII newline, while KEY_ENTER represents a keyboard code. See the PDCurses code.
For more information, you should post the relevant part of your code.

Related

How do I get char directly from keyboard not through buffer?

I am making a game which has a character moves in 4 directions: up, down, left, right corresponding to W,S,A,D on the keyboard. The problem is when using getch() to get input from buffer, it always has a pause time after the first single keypress. For instance, when I hold 'A' button, it acts like: A(a short period of time)AAAAAAAAA.
How do I get rid of that delay time?
Any help would be appreciated.
(Answers in either C or C++ are all acceptable, since I am using graphics.h for this program, which requires C++ to run, but I mainly code in C).
I am using windows 10 64 bits.
For a non-blocking getch method I personally use this piece of code (in C):
#include <conio.h>
int getch_noblock(){
return _kbhit() ? _getch() : -1;
}
the _kbhit() method returns 0 if no key are pressed, otherwise returns a number if the keyboard input buffer is not empty.
the _getch() method read a char from the keyboard buffer.
It works only for Windows.
Documentation:
_khbit(): https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/kbhit?view=msvc-170
_getch(): https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getch-getwch?view=msvc-170
By the way, surfing on the web I found an interesting method, but I've never tried or seen it:
https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getch-nolock-getwch-nolock?view=msvc-170
getch() already bypasses buffer:
Prototype
int _getch(void);
Description
_getch obtains a character from stdin. Input is unbuffered, and this
routine will return as soon as a character is available without
waiting for a carriage return. The character is not echoed to stdout.
_getch bypasses the normal buffering done by getchar and getc.
And for your problem, as someone already said, you can use the kbhit() method

C++ use cin.get to get a character, but not end the while loop when encounter the EOF

The following is my code, that I want to read characters from stdin, and end when it meet an EOF(ctrl-z).
#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
using namespace std;
int main()
{
string article ;
char nextChar;
while( cin.get(nextChar) ) {
if( cin.eof() ) break ;
article.append(1, nextChar) ;
}
cout << article ;
system("pause") ;
}
I test an input like this:
I am a student.<ctrl-z>
And then I press enter, but it does not halt.
When I type another [ctrl-z], and then press neter.
It just can exit from the while loop.
Why the first [ctrl-z] not to signal the eof condition?
The following explanation is slightly simplified.
It's a feature of your operating system. This is how your operating system works.
An end of file is, really, the underlying read() system call returning 0. An end of file is not CTRL-Z. CTRL-Z gets interpreted by your operating system to flush its interactive key buffer, and have the process read() its contents.
When you type in a terminal, the process does not actually end up reading anything until Enter is pressed. At that time the read() system call completes, and returns everything that's been read. In general, before pressing Enter you can backspace and edit what you typed, and your program has no indication that you've edited anything, all that it read()s is the final contents of the line after pressing Enter.
If you type something, and press CTRL-Z, the typed input is also read() by the program as if it was typed in.
Only if nothing is typed, and CTRL-Z is pressed, does the underlying read() system call returns 0, because nothing got typed in first; this is interpreted as an end-of-file indication. But if something gets typed in first, CTRL-Z needs to be entered twice, once to read() the typed in input, and clear the input buffer, then CTRL-Z a second time, to cause an read() of 0.
By the way, your code has a harmless bug. If cin.get() succeeds, cin.eof() can never be true.

Why can't I end my input by this?

I want to terminate my input by input, EOF(^Z in windows), and here is the program:
#include<stdio.h>
#include<conio.h>
int main(void)
{
int c;
while ((c = getchar()) != EOF)
{
if (c == '\t')
{
putchar('\\');
putchar('t');
}
else if (c == '\b')
{
putchar('\\');
putchar('b');
}
else if (c == '\\')
{
putchar('\\');
putchar('\\');
}
else if (c == '\r')
{
puts("\\n");
// putchar('\n');
}
else{
putchar(c);
}
}
return 0;
}
and here is my input and output:
So I am asking: why can't I terminate my input by the first ^Z? Otherwise stated, why do I have to type enter to make a new line in order to terminate my input by input at ^Z?
See the discussions in:
read() from stdin doesn't ignore newline
How can I make the word count program (from K&R) terminate after just one application of Control-D
How to simulate EOF without preceding newline in C
On Unix, Control-D is (by default) equivalent to Control-Z on Windows.
All point out that the first time you type Control-Z, the input already accumulated in the input is sent to the program (without a newline); there is a non-zero number of characters sent, so it is not yet EOF. The second time, you type the Control-Z at the beginning of the line, and the program gets zero bytes to read, which is interpreted as EOF.
There's no real reason beyond "that's how it works". You can just press F6 instead though. That will be seen as signaling the end of file, even if it's not preceded by an enter.
The reason you have to press both F6 and enter is fairly simple: there are really two separate pieces of code involved here. The operating system has a small (somewhat crippled) editing routine that lets you enter a line of data. It has code to process back-space and a few things like that, so you can use them when entering data, even though your code doesn't include any editing capability at all. That routine returns a line of text to your program, but only when you've entered what it is programmed to "think of" as a completely line--and that only happens when enter is pressed.
Once that buffer full of data has been read in by the operating system, it's sent to your program. Your program looks at the contents, and when/if it finds the ctrl+Z, it reads that as signaling the end of the file. But, since the end of file processing is done by your program, not the operating system's editing routine, there's no way for it to be senses until you've pressed enter.
If you really don't like this behavior, most operating systems do provide some way to do un-buffered reading. The exact way varies by operating system though. One Windows, you can use _getch. Most Unix-based systems provide roughly the same capabilities in the Curses library (and if you want to use that, there's also at least one free implementation of curses for Windows).

What code should be used instead of getche in c++

I am new to c++ ,
What code should i write to make the screen stand still. I use
getche();
in c language. but instead of getche() what should i use in c++;
I tried
std::cin.get();
but the console windows displays and then goes off quickly.
the console windows displays and then goes off quickly.
It seems that you have something in your buffer, and cin.get is reading that as a character. For example:
int i = 0;
std::cin >> i;
std::cin.get();
When you enter number and press Enter, cin >> i will consume the number, but it will leave \n character (which comes from Enter keystroke) in the buffer which will be read by std::cin.get() without waiting for the user to enter new data.
In order to make this example to behave like we want, we need to empty the buffer before calling std::cin.get():
int i = 0;
std::cin >> i;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
std::numeric_limits is defined in <limits> header file.
In Windows, I usually uses system("pause");, which call the OS's pause command, to prevent the console window from being closed after the program terminates. This commands displays a nice message and wait for any key :).
Press any key to continue . . .
I don't know if the command exists in the other OSes or not, nor I don't know if it is what you're trying to archive :).
The function is in the cstdlib or stdlib.h header file
Last but not least, it's not really a good idea to call getch() at the last line of code to prevent the console from being closed. But if you really prefer this way, I suggest to use something like
std::string temp;
std::cin>>temp;
At the ends of your main function, just before return statement.
Just include <stdlib.h> and in main method use system("pause") your console window will remain still.
Please use the following
getch()

Capture stdin input without echoing characters to screen

I have a very simple code:
char character;
std::cin >> character;
However, I would like it to behave as follow:
Don't echo to console the character I type
std::cin should return (unblock) right away when a character is pressed without having to press the Enter key
Is this possible? I also have access to Qt.
This is going to be platform dependent, but you can use
getch() which is part of conio.h if you're on windows
or
getch() as part of curses.h if you're on *nix
References
http://opengroup.org/onlinepubs/007908799/xcurses/curses.h.html
http://en.wikipedia.org/wiki/Conio.h