Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting input from console without cin?

Tags:

c++

c

console

I'm trying to make a little console program that will basically be console pong. So right now I have this:

int main()
{
    while(1)
    {
        clearScreen();
        restThread(100);
    }
    return 0;
}

The only input I need to poll is if the user has pressed the A or D key since the screen was cleared. I will also need to know when the key is released. I'm also trying to do this cross platform.

so really all I need is like an if(keyWasDown('a')) {} sort of function.

Thanks

like image 702
jmasterx Avatar asked Jan 21 '11 01:01

jmasterx


People also ask

How do you take input until Enter is pressed in C++?

The standard C++ I/O libraries only have functions that read input from a stream, which means to get a string on a console, enter key should be pressed. If you want to get the input without pressing enter key, you have to use nonstandard functions like _getch() in <conio. h> in Windows.

Is Cin an input?

The "c" in C++ cin refers to "character" and "in" means "input". Thus, cin means "character input". The C++ cin object belongs to the istream class. It accepts input from a standard input device, such as a keyboard, and is linked to stdin, the regular C input source.

How do you take CIN input?

It is used to accept the input from the standard input device i.e. keyboard. It is associated with the standard C input stream stdin. The extraction operator(>>) is used along with the object cin for reading inputs. The extraction operator extracts the data from the object cin which is entered using the keyboard.

How do you continue reading lines until there is no more input?

The cin function would return false if there is no more lines for input. You can do the following to read until the end of input, or eof if you are redirecting cin to read from a file. You could do freopen("filename", "r",m stdin); to redirect the input.


1 Answers

Maybe you want kbhit (non-blocking) or getch (blocking), both from <conio.h>. There's also getchar, from <stdio.h> or <cstdio>.

If you want the program to wait for a keyboard press, getch or getchar by themselves will do.

If you don't want the program to wait for a keyboard press, kbhit combined with either getch or getchar will suffice.

However, as GMan said, these methods are not really cross platform (if you never intend to try this on different platforms, that's moot, really). For console games, you might be interested looking into ncurses.

like image 75
Zach L Avatar answered Sep 28 '22 22:09

Zach L