1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
#include <windows.h>
#include <cstdio>
#include <cstdlib>
// Takes an array to store the data in, and the number of characters to store
void getInput(LPSTR& lpszInput, WORD wNumChars) {
HANDLE hStdIn, hStdOut; // Console handles
DWORD consoleMode; // Stores the old console mode
LPSTR lpszPrompt = (LPSTR)"Type text: "; // text to display
CHAR chBuffer[1]; // buffer for input, means one char at a time
LPSTR chInput = new CHAR[wNumChars]; // temporary buffer
DWORD cRead, cWritten; // number of characters read / written
WORD wCharacters = 0; // number of characters read so far
// Fill with null terminators in the case of a Ctrl+C to stop overflows
ZeroMemory(chInput, wNumChars);
// Get the console handles
hStdIn = GetStdHandle(STD_INPUT_HANDLE);
hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
// Write the prompt to the screen
if (!WriteFile(hStdOut, lpszPrompt, lstrlenA(lpszPrompt),
&cWritten, NULL)) {
MessageBox(NULL, "WriteFile", "Console Error",
MB_OK | MB_ICONERROR);
exit(1);
}
// Get the current console mode, save it for later
if (!GetConsoleMode(hStdIn, &consoleMode)) {
MessageBox(NULL, "GetConsoleMode", "Console Error",
MB_OK | MB_ICONERROR);
exit(1);
}
// Set out own console mode
if (!SetConsoleMode(hStdIn, ENABLE_PROCESSED_INPUT)) {
MessageBox(NULL, "SetConsoleMode", "Console Error",
MB_OK | MB_ICONERROR);
exit(1);
}
// While there is room in the buffer and reading hasn't failed
while (wCharacters < wNumChars &&
ReadFile(hStdIn, chBuffer, 1, &cRead, NULL)) {
// increment the number of characters read
wCharacters += cRead;
if (wCharacters == 0)
continue;
// We are using a buffer size 1, and newline is 2 chars ("\r\n"), so lets fix that
if (*chBuffer == '\r') *chBuffer = '\n';
// Copy the input into the temporary buffer
chInput[wCharacters - 1] = *chBuffer;
// Write what we input to the console (otherwise nothing appears)
if (!WriteFile(hStdOut, chBuffer, cRead, &cWritten, NULL))
break;
}
// copy our temporary buffer to the parameter passed
strcpy(lpszInput, chInput);
// reset the console mode to what it was before
if (!SetConsoleMode(hStdIn, consoleMode)) {
MessageBox(NULL, "SetConsoleMode", "Console Error",
MB_OK | MB_ICONERROR);
exit(1);
}
}
int main() {
// example usage
CHAR chText[10];
getInput(chText, 10);
printf(" : %s", chText);
return EXIT_SUCCESS;
}
|