Date: 2016mar1
OS: Windows
Keywords: ReadConsoleInput, WriteConsoleInput
Q. How can I read/write from the console?
A. Here is a class that does that.
--- console.h ---
class Console
{
private:
HANDLE m_hStdin;
HANDLE m_hStdout;
public:
Console();
char getch();
BOOL putch(const char c);
BOOL puts(LPCSTR);
}
--- console.cpp ---
#include "console.h"
Console::Console()
{
m_hStdin = GetStdHandle(STD_INPUT_HANDLE);
m_hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
}
char Console::getch()
{
INPUT_RECORD input_record;
DWORD bytes_read = 0;
for (;;)
{
if (!ReadConsoleInput(m_hStdin, &input_record, 1, &bytes_read)) return -1;
}
return input_record.Event.KeyEvent.uChar.AsciiChar;
}
BOOL Console::putch(const char c)
{
char buf[2] = { c };
DWORD written;
DWORD unused;
BOOL bResult;
bResult = WriteConsole(
m_hStdout,
buf,
1,
&written,
&unused);
if (!bResult) return FALSE;
return written == 1;
}
BOOL Console::puts(LPCSTR s)
{
BOOL bResult = TRUE;
for (LPCSTR p = s; *p; p++)
{
if (!putch(*p)) bResult = FALSE;
}
return bResult;
}